英文:
go:embed fs only works for the root with http server?
问题
我有以下的目录结构:
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 获取到 index.html 的内容。然而,当我将代码改为以下内容时:
mux.Handle("/admin/", http.FileServer(http.FS(sub)))
当访问 http://127.0.0.1:2222/admin/ 时,我得到了 404 错误。
英文:
I have the following directory structure:
web/
dist/
index.html
main.go
the content of 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)
}
When the code is run, I could get the content of index.html through http://127.0.0.1:2222. However, when I changed the line to:
mux.Handle("/admin/", http.FileServer(http.FS(sub)))
I get 404 when accessing http://127.0.0.1:2222/admin/.
答案1
得分: 2
你需要从请求路径中去掉/admin/
(否则文件服务器将在web/dist/admin
中查找)。例如:
mux.Handle("/admin/", http.StripPrefix("/admin/", http.FileServer(http.FS(sub))))
有关更多信息,请参阅StripPrefix
的文档。
英文:
You will need to strip the /admin/
off the request path (otherwise the file server will be looking in web/dist/admin
). e.g.
mux.Handle("/admin/", http.StripPrefix("/admin/", http.FileServer(http.FS(sub))))
See the docs for StripPrefix
for more info.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论