go:嵌入式fs只适用于http服务器的root用户



我有以下目录结构:

web/
dist/
index.html
main.go

main.go:的内容

package main
import (
"embed"
"io/fs"
"net/http"
)
//go:embed web/dist
var webfs embed.FS
func main() {
mux := http.NewServeMux()
sub, err := fs.Sub(webfs, "web/dist")
if err != nil {
panic(err)
}
mux.Handle("/", http.FileServer(http.FS(sub)))
http.ListenAndServe(":2222", mux)
}

当代码运行时,我可以通过http://127.0.0.1:2222.然而,当我把行改为:

mux.Handle("/admin/", http.FileServer(http.FS(sub)))

访问时我得到404http://127.0.0.1:2222/admin/.

您需要将/admin/从请求路径中删除(否则文件服务器将在web/dist/admin中查找(。例如

mux.Handle("/admin/", http.StripPrefix("/admin/", http.FileServer(http.FS(sub))))

有关更多信息,请参阅StripPrefix的文档。

相关内容

最新更新