2

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

4

1 回答 1

1

我怀疑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(如在那些测试中),请将其用于特定路径,而不是通用“ /”。

于 2015-05-05T11:47:28.290 回答