Go: Gorilla Mux how to get URL params

3 min readNov 5, 2018

I have been working on creating a web application with Go. I am currently making rest calls to multiple APIs that retrieve information. Once I get the data I extract, transform and load the data into a repository. I ran into a problem when I needed to pull out the path from the URL and decided to try gorilla mux. In this guide I will explain:

  1. Gorilla Mux
  2. URL params
  3. Passing data to template

What is Gorilla Mux?

Gorilla is a tool-kit that has packages to help with routing, session, websockets and much more. In this guide I will be talking about Gorilla Mux, which is a powerful web router and dispatcher.

Gorilla Mux Documentationhttp://www.gorillatoolkit.org/pkg/mux

How do you register routes?

We need something to register the routes to, I think the mux router would be a great tool to use, so lets create a NewRouter.

Now that we have a router lets register some routes

This should look very similar to net/http, if you want to learn more about net/http check out the below link:

net/http https://medium.com/@tommarler/go-rendering-html-templates-fff8457780db

What does the HandleFunc do?

It registers the URL path and handler, if a incoming URL request matches one of the paths it will call the handler. For I go to /home the HomePage handler will be called.

Can a path have a variable?

Yes, you define a route and pass a variable to that route to represent a path.

How do I get the variable from the path?

If I wanted to the display the id from “/propublica/{id}”, I would use mux.Vars().

I get the id from the path, store it in a variable called id and passs it to the template called showSenatorDetails.html.

The value: 123213 is the id from the path URL.

I hope you learned about gorilla mux and how easy it is to get the path from the URL. Let me know what you think, if you would like to learn more about go check out the below links. See you in the next article.

Please checkout the below links

Go: Buffalohttps://medium.com/@tommarler/go-buffalo-web-development-eco-system-5a697e1b1ceb

Go: Jsonhttps://medium.com/p/13880dc1f1f8?source=your_stories_page---------------------------

Go: XML and SEOhttps://medium.com/@tommarler/go-xml-and-seo-4adc5226d606




iOS Developer, Go, Java, C#, Blockchain enthusiast, Data junkie