What is the difference between PathPrefix() and Handle(pathString, ...) in gorilla/mux?
Asked Answered
J

1

5

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.

Joe answered 3/7, 2018 at 19:58 Comment(0)
B
6

Router vs. Route

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.

PathPrefix() vs. Path()

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.

Router.Handle() vs. Router.Path().Handler()

Router.Handle() is a shortcut for, and therefore equivalent to, executing Router.Path() followed by a call to Route.Handler() on the returned Route.

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.

Serving files from a path with a prefix

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.

Bluestone answered 4/7, 2018 at 0:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.