我最近询问了有关使用 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 处理结合起来?