【问题标题】:Serving static content and handling 404 not found with Gorilla toolkit使用 Gorilla 工具包找不到提供静态内容和处理 404
【发布时间】:2015-05-05 11:41:35
【问题描述】:

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

【问题讨论】:

  • 你的目录结构是什么?
  • 已添加到问题中

标签: go gorilla


【解决方案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(如those tests),请将其用于特定路径,而不是通用的“/”。

【讨论】:

  • 谢谢冯,我也怀疑过。我们想要提供一个根 index.html 页面,因此在浏览器中输入“localhost:8888”会为用户提供静态内容。因此 r.PathPrefix("/").Handler()。是否有替代“/”的方法可以允许 404 处理和提供静态内容?
  • @CloomMagoo 是的,但副作用是永远不会调用 NotFoundHandler
  • @CloomMagoo 代表“/”,使用 mux.HandleFunc("/", ...),而不是 PathPrefix
  • 要使用 HandleFunc 而不是 PathPrefix,为静态目录提供服务的实际处理程序 func 会是什么样子?我会调查,但如果你有一个例子,我会很感激。谢谢。
  • @CloomMagoo 就像任何其他 httpHandler 函数一样。
猜你喜欢
  • 2013-03-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2016-01-21
  • 2018-11-12
  • 1970-01-01
  • 2011-09-17
相关资源
最近更新 更多