Golang Gorilla mux with http.FileServer returning 404

左心房为你撑大大i 提交于 2019-11-28 20:18:10
dodgy_coder

I posted this on golang-nuts discussion group and got this solution from Toni Cárdenas ...

The standard net/http ServeMux (which is the standard handler you are using when you use http.Handle) and the mux Router have different ways of matching an address.

See the differences between http://golang.org/pkg/net/http/#ServeMux and http://godoc.org/github.com/gorilla/mux.

So basically, http.Handle('/images/', ...) matches '/images/whatever', while myRouter.Handle('/images/', ...) only matches '/images/', and if you want to handle '/images/whatever', you have to ...

  1. set a regular expression match in your router or
  2. use the PathPrefix method on your router, like:

Code examples

1.

myRouter.Handle('/images/{rest}', 
    http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/")))
)

2.

myRouter.PathPrefix("/images/").Handler(
    http.StripPrefix("/images/", http.FileServer(http.Dir(HomeFolder + "images/")))
)

As of May 2015 gorilla/mux package still have no version releases. But problem is different now. It is not that myRouter.Handle does not match url and needs regexp, it does! But http.FileServer requires prefix to be removed from url. Below example works fine.

ui := http.FileServer(http.Dir("ui"))
myRouter.Handle("/ui/", http.StripPrefix("/ui/", ui))

Note, there is no /ui/{rest} in abowe example. You may also wrap http.FileServer into logger gorilla/handler and see request to coming to FileServer and response 404 going out.

ui := handlers.CombinedLoggingHandler(os.Stderr,http.FileServer(http.Dir("ui"))
myRouter.Handle("/ui/", ui) // getting 404
// works with strip: myRouter.Handle("/ui/", http.StripPrefix("/ui/", ui))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!