[英]Remove trailing slash from urls - Go static server
I've set up a simple Go static file server with http.FileServer
.我已经使用 http.FileServer 设置了一个简单的
http.FileServer
static 文件服务器。 If I have a directory structure like public > about > index.html
, the server will correctly resolve /about
to about > index.html
, but it adds a trailing slash so the url becomes /about/
.如果我有一个像
public > about > index.html
这样的目录结构,服务器将正确解析/about
为about > index.html
,但它添加了一个斜杠,因此 Z572D4E421E5E6B9BC11D815E 变为/about/
8 。
Is there a simple way to remove these trailing slashes when using http.FileServer
?使用
http.FileServer
时,有没有一种简单的方法可以删除这些斜杠? Ultimately, it works either way - it's mostly just a personal preference to not have the trailing slashes if possible.最终,它可以以任何一种方式工作——如果可能的话,不使用尾部斜杠主要是个人喜好。
When you register the route /about/
an implicit route of /about
is added (which redirects clients to /about/
).当您注册路由
/about/
时,会添加/about
about 的隐式路由(将客户端重定向到/about/
)。
To work around this, you can register two explicit routes:要解决此问题,您可以注册两个显式路由:
/about
to serve your index.html
/about
为您的索引提供服务index.html
/about/
to serve the http.FileServer
to handle any HTML assets for the page /about/
服务于http.FileServer
以处理页面的任何 HTML 资产like so:像这样:
// 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 https://play.golang.org/p/WLwLPV5WuJm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.