Golang 文件服务器抛出未找到

Golang fileserver throws not found

我正在尝试提供一些字体,但是当我访问 localhost:4000/fonts 时,它显示 404 not found。我的代码:


    fs := http.FileServer(http.Dir("./fonts"))

    http.Handle("/fonts", http.StripPrefix("/fonts/", fs))

    http.Handle("/", app.routes())

    log.Println("Serving at localhost:4000...")
    log.Fatal(http.ListenAndServe(fmt.Sprintf("localhost:%d", cfg.Port), nil))

更新

如果我从“/”而不是“/fonts”提供服务,它就可以工作。但我希望它从“/字体”开始工作。

您不应该去掉字体后的尾部斜杠,因为您希望结果是 /file 而不是 file.

出于同样的原因,您还应该将尾部斜杠添加到处理程序路径中。

http.Handle("/fonts/", http.StripPrefix("/fonts", fs))

如前所述,这两项更改的目的都是为您提供一个类似于 /somefile 的路径,该路径是针对 filesevers 文件系统查找的。