我有以下目录结构:
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
的文档。