我已经使用http.FileServer
设置了一个简单的Go静态文件服务器。如果我具有public > about > index.html
之类的目录结构,则服务器会将正确的/about
解析为about > index.html
,但它会在末尾添加一个斜杠,从而使URL成为/about/
。
使用http.FileServer
时,是否有一种简单的方法可以删除这些尾部斜杠?最终,它会以任何一种方式起作用-如果可能的话,多数情况下只是出于个人喜好而不使用斜杠。
最佳答案
当您注册路由/about/
时,会添加一个隐含的/about
路由(它将客户端重定向到/about/
)。
要变通解决此问题,您可以注册两个显式路由:
/about
服务您的index.html
/about/
提供http.FileServer
来处理页面像这样:
// 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://play.golang.org/p/WLwLPV5WuJm
关于http - 从网址中删除结尾的斜杠-转到静态服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62642098/