`go:embed fs` 只适用于根目录的 HTTP 服务器吗?

huangapple go评论74阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2022年8月4日 04:25:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/73227440.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定