我用http.FileServer设置了一个简单的Go静态文件服务器。如果我有一个类似public > about > index.html的目录结构,服务器将正确地将/about解析为about > index.html,但是它会添加一个尾随斜杠,从而使url变成/about/。
在使用http.FileServer时,是否有一种简单的方法来删除这些拖尾斜杠?最终,无论是哪种方式,它都是可行的--如果可能的话,不使用尾随斜杠只是个人偏好。
发布于 2020-06-29 18:58:44
注册路由/about/时,会添加/about的隐式路由(它将客户端重定向到/about/)。
要解决此问题,您可以注册两个显式路由:
/about为您的index.html/about/提供服务,为http.FileServer处理页面的任何HTML资产。
就像这样:
// what you had before
h.Handle("/about/",
http.StripPrefix(
"/about/",
http.FileServer(http.Dir("/tmp/about-files")),
),
)
// prevents implicit redirect to `/about/`
h.HandleFunc("/about",
func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html") // serves a single file from this route
},
)https://stackoverflow.com/questions/62642098
复制相似问题