duankan8739 2015-05-05 11:41
浏览 44

提供静态内容并处理Gorilla工具箱找不到的404

I recently asked about serving static content and handling 404 with Gorilla mux; when using Handle instead of PathPrefix, the app can serve the root page (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)
}

However requests for pages within the root page (e.g. http://localhost:8888/demo/page1.html) get intercepted by the 404 handler. Is there any way to prevent this, while catching requests for non-existent pages or services? This is the directory structure:

...
main.go
static\
  | index.html
  demo\
    page1.html
    demo.js
    demo.css
    | jquery\
       | <js files>
    | images\
       | <png files>

Previous Question:

I am using the Gorilla mux toolkit to handle http requests in a web server app:

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)
}

I want to add a handler for invalid URLS, but it is never called:

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)
}

If I remove the static handler, the not found handler is called. However, the app needs to serve the static content, from a non-absolute path. Is there a way to combine that with 404 handling?

  • 写回答

1条回答 默认 最新

  • duanbu1421 2015-05-05 11:47
    关注

    I suspect r.PathPrefix("/").Handler() would match any path, making the notfound handler useless.

    As mentioned in "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.
    

    If you are using PathPrefix (as in those tests), use it for a specific path, not for the generic "/".

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测