我最近询问了有关使用 Gorilla mux 提供静态内容和处理 404 的问题;当使用 Handle 而不是 PathPrefix 时,应用程序可以提供根页面 ( http://localhost:8888 ):
func main() {
r := mux.NewRouter()
r.HandleFunc("/myService", ServiceHandler)
r.Handle("/", http.FileServer(http.Dir("./static")))
r.NotFoundHandler = http.HandlerFunc(notFound)
l, _ := net.Listen("tcp", "8888")
http.Serve(l, r)
}
然而,对根页面中页面的请求(例如 http://localhost:8888/demo/page1.html )会被 404 处理程序拦截。有什么办法可以防止这种情况,同时捕获对不存在的页面或服务的请求?这是目录结构:
...
main.go
static\
| index.html
demo\
page1.html
demo.js
demo.css
| jquery\
| <js files>
| images\
| <png files>
上一个问题:
我正在使用 Gorilla mux 工具包来处理 Web 服务器应用程序中的 http 请求:
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)
}
我想为无效的 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
处理程序无用。
如“route.go
”中所述:
// 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.
如果您使用 PathPrefix
(如 those tests ),请将其用于特定路径,而不是通用的“/
”。
关于go - 提供静态内容并处理 404 not found with Gorilla toolkit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30052002/