提供静态内容并处理Gorilla toolkit中找不到的404
我最近询问了关于使用Gorilla mux提供静态内容和处理404的问题;使用句柄而不是PathPrefix时,应用程序可以服务于根页面(): 但是,根页面(例如)内的页面请求会被404处理程序截获。在捕获对不存在的页面或服务的请求时,是否有任何方法可以防止这种情况?这是目录结构:提供静态内容并处理Gorilla toolkit中找不到的404,go,gorilla,Go,Gorilla,我最近询问了关于使用Gorilla mux提供静态内容和处理404的问题;使用句柄而不是PathPrefix时,应用程序可以服务于根页面(): 但是,根页面(例如)内的页面请求会被404处理程序截获。在捕获对不存在的页面或服务的请求时,是否有任何方法可以防止这种情况?这是目录结构: ... main.go static\ | index.html demo\ page1.html demo.js demo.css | jquery\ | &l
...
main.go
static\
| index.html
demo\
page1.html
demo.js
demo.css
| jquery\
| <js files>
| images\
| <png files>
我想为无效URL添加处理程序,但从未调用过:
func main() {
r := mux.NewRouter()
r.HandleFunc("/myService", ServiceHandler)
r.NotFoundHandler = http.HandlerFunc(notFound)
r.PathPrefix("/").Handler(http.FileServer(http.Dir("static")))
l, _ := net.Listen("tcp", "8888")
http.Serve(l, r)
}
如果移除静态处理程序,则调用未找到的处理程序。但是,应用程序需要从非绝对路径提供静态内容。有没有办法将其与404处理相结合 我怀疑
r.PathPrefix(“/”).Handler()
会匹配任何路径,使得notfound
处理程序无效
如“”所述:
如果您使用的是
PathPrefix
(如中),请将其用于特定路径,而不是通用的“/
”您的目录结构是什么?添加到问题中谢谢,我也怀疑这一点。我们希望为root index.html页面提供服务,因此在浏览器中输入“”将为用户提供静态内容。因此,r.PathPrefix(“/”).Handler()。是否有一种替代“/”的方法允许404处理和服务静态内容?@CloomMagoo是的,但其副作用是永远不会调用NotFoundHandler
。@CloomMagoo对于“/”,使用mux.HandleFunc(“/”,…)
,而不是PathPrefix
使用HandleFunc而不是PathPrefix,为静态目录提供服务的实际处理程序func是什么样子的?我会调查的,但如果你有一个例子,我会很感激的。谢谢。@CloomMagoo和其他httpHandler函数一样。
func main() {
r := mux.NewRouter()
r.HandleFunc("/myService", ServiceHandler)
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./static")))
l, _ := net.Listen("tcp", "8888")
http.Serve(l, r)
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/myService", ServiceHandler)
r.NotFoundHandler = http.HandlerFunc(notFound)
r.PathPrefix("/").Handler(http.FileServer(http.Dir("static")))
l, _ := net.Listen("tcp", "8888")
http.Serve(l, r)
}
// Note that it does not treat slashes specially
// ("`/foobar/`" will be matched by the prefix "`/foo`")
// so you may want to use a trailing slash here.