Reputation: 725
I noticed that there are two ways to specify a path in the gorilla/mux
router:
r.PathPrefix("/api").Handler(APIHandler)
And:
r.Handle("/api", APIHandler)
What is the difference?
Also, I don't understand the difference between a router and a route in the context of gorilla/mux
.
PathPrefix()
returns a route, which has a Handler()
method. However, we cannot call Handler()
on a router, we must call Handle()
.
Look at the following example:
r.PathPrefix("/").Handler(http.FileServer(http.Dir(dir+"/public")))
I am trying to serve static files from a public directory. The above expression works without any problem. My HTML and JavaScript are served as expected. However, once I add something to the path, e.g.
r.PathPrefix("/home").Handler(http.FileServer(http.Dir(dir+"/public")))
Then I am getting 404, not found error on localhost:<port>/home
.
Upvotes: 5
Views: 5489
Reputation: 6877
Router
is a container within which you can register multiple Route
instances. The Route
interface is largely replicated on Router
to enable easy creation of Route
instances in the Router
.
Note that all of the Router
methods that have the same name as a Route
method are wrappers around Router.NewRoute()
, which returns a new Route
registered to the Router
instance.
For comparison, when you call such methods on an existing Route
instance, it returns the same instance for chaining method calls.
When you specify a path using PathPrefix()
it has an implicit wildcard at the end.
A quote from the overview section of the documentation:
Note that the path provided to PathPrefix() represents a "wildcard": calling PathPrefix("/static/").Handler(...) means that the handler will be passed any request that matches "/static/*".
On the other hand, when you specify a path using Path()
, there's no such implied wildcard suffix.
Note that this is not the same as calling Router.PrefixPath()
followed by a call to Route.Handler
, since Router.Handle()
does not provide the wildcard suffix.
For your last example, try changing:
r.PathPrefix("/home").Handler(http.FileServer(http.Dir(dir+"/public")))
To:
r.PathPrefix("/home/").Handler(http.StripPrefix("/home/", http.FileServer(http.Dir(dir+"/public"))))
Otherwise, it's trying to serve files from dir + "/public" + "/home/"
An example of this is in the documentation, halfway through the overview.
Upvotes: 6