
Golang Gorilla Mux is a powerful and flexible router for building web applications. It's widely used in the Go community due to its simplicity and high performance.
Gorilla Mux is designed to be highly customizable, allowing developers to create routes with parameters, path prefixes, and HTTP methods. This flexibility makes it an ideal choice for complex web applications.
One of the key features of Gorilla Mux is its ability to handle multiple routes with the same path prefix. For example, it can handle routes like "/users" and "/users/{id}" simultaneously.
Check this out: Go Programming Language Web Development
Getting Started
To get started with gorilla/mux, you need to install it using the go get command. Create a new file at ./cmd/gorilla/main.go, and you'll have both examples side by side.
The directory tree should look like you have a new file in the /cmd/gorilla folder, and the standard library example in the /cmd/standardlib folder. You can choose a different port to run both tutorials simultaneously.
By using gorilla/mux, you can specify the HTTP verb and define URL parameters in a way that mimics the standard library, but adds extra routing capabilities.
Check this out: Gorilla Websocket
Importing the Package
To use gorilla/mux, we need to import it. The first step is to initialize our go.mod file with the command.
We need to provide a URL, but it's not important yet. We're not hosting this in a remote repository, so we can just use a placeholder URL.
To use a remote repository, we would provide a path to our repository, such as github.com/username/mypackage.
Consider reading: Golang Use Cases
Why Use This Package?
So you're wondering why you should use this package? It's because it can extract variables from the URL path.
One of the main reasons is that it supports subrouters, which you can use to group similar routes. This makes it easier to organize your code and keep things tidy.
It also matches routes via domains, prefixes, methods, and more. This gives you a lot of flexibility when it comes to setting up your routes.
The learning curve isn't steep, thanks to the package implementing the http.Handler interface, making it compatible with the standard library. This means you can easily integrate it with your existing code.
If this caught your attention, see: Create a Package in Golang

Here are some of the most used features of the package at a glance:
- Extract variables from the URL path
- Supports subrouters for grouping similar routes
- Matches routes via domains, prefixes, methods, and more
- Easy to learn and integrate with the standard library
With a mature package like this, you'll have an extensive userbase to turn to when you get stuck.
Getting Started
To get started with building a REST API, you'll first need to install gorilla/mux using the go get command. This will allow you to take advantage of the extra routing capabilities that gorilla/mux offers.
Create a new file at ./cmd/gorilla/main.go, and make sure your directory tree looks like the one described in the example. This will give you a clean slate to work with.
To create a new router, simply call mux.NewRouter(). This will give you a basic router that you can use to start building your API.
You can specify the HTTP verb for a particular route by using the HandleFunc method. For example, you can define a route for GET requests using HandleFunc. This will allow you to handle different types of requests in a single application.
Discover more: How to Update a Github Using Golang

To define URL parameters, use the format {name:regex} in your route. The regex part is optional, and if omitted, the router will match until the next /. This gives you a lot of flexibility when it comes to defining your routes.
Once you've set up your router and defined your routes, you can start the server on a specific port. For example, you can start the server on port 8010, just like in the example. By choosing a different port, you can have multiple servers running simultaneously.
Full Example
In this section, we'll dive into a full example of a small mux-based server, which will give you a better understanding of how to use gorilla/mux in your project.
Here's a complete, runnable example of a small mux-based server, as shown in Example 2.
Let's register a couple of URL paths and handlers, as explained in Example 4. This is equivalent to how http.HandleFunc() works, where if an incoming request URL matches one of the paths, the corresponding handler is called passing (http.ResponseWriter, *http.Request) as parameters.
Discover more: Url Golang

Paths can have variables, defined using the format {name} or {name:pattern}. For example, if a regular expression pattern is not defined, the matched variable will be anything until the next slash.
Here are some examples of paths with variables:
In the above table, the first path will match any value for {isbn} until the next slash, while the second path will only match values that match the pattern defined in {isbn:pattern}.
Routing
Routing is a fundamental aspect of building web applications with Go and the Gorilla Mux package. You can register routes with a matcher for HTTP methods using the Methods function, which accepts a sequence of one or more methods to be matched, such as "GET", "POST", "PUT".
The StrictSlash function defines the trailing slash behavior for new routes. When true, if the route path is "/path/", accessing "/path" will perform a redirect to the former and vice versa.
You can use the PathPrefix function to add a matcher for the URL path prefix. This matches if the given template is a prefix of the full URL path. Note that it does not treat slashes specially, so you may want to use a trailing slash here.
If this caught your attention, see: Golang Use .env File
The Router's Host function registers a new route with a matcher for the URL host. You can also use the Route's Host function to add a matcher for the URL host.
Here are some examples of matchers that can be used to restrict routes:
- Host: to match a specific host or domain
- PathPrefix: to match a specific path prefix
- Methods: to match specific HTTP methods
- URL schemes: to match specific URL schemes
These matchers can be combined in a single route to create more complex routing rules. Routes are tested in the order they were added to the router, so the first one that matches wins.
Subrouters can be used to create domain or path "namespaces". You can define subrouters in a central place and then parts of the app can register its paths relatively to a given subrouter.
Here's an example of how to use subrouters:
```markdown
subrouter := router.PathPrefix("/admin").Subrouter()
subrouter.HandleFunc("/users", usersHandler)
subrouter.HandleFunc("/products", productsHandler)
```
This will only match the routes "/admin/users" and "/admin/products" if the host is "www.example.com".
Handling Requests
To implement handlers, you'll need to define two generic handlers for InternalServer errors and NotFound errors. These handlers return HTTP code 500 and 404, respectively.
The code for implementing handlers is almost identical to the code used in part one, so you can use the same techniques to build the methods. You'll start by defining the handlers to deal with errors.
To create a URL-friendly recipe name, you'll use the slugify function from gosimple/slug. This will help you create a unique ID for each recipe.
A different take: Golang Code Comment Specifications
Queries
Queries are a powerful tool for handling requests, and they work by adding a matcher for URL query values.
You can think of it like a filter that only allows certain URLs to pass through. For example, if you have a route that looks like this: The above route will only match if the URL contains the defined queries values, e.g.: ?foo=bar&id=42.
You can also use empty strings as values to match any value if the key is set, like this: If the value is an empty string, it will match any value if the key is set.
Variables can be used to define an optional regexp pattern to be matched, giving you even more flexibility in how you handle requests.
Here's an interesting read: Golang Set Env Variable
Handling Cors Requests
Handling CORS requests can be a bit tricky, but it's essential for making your API accessible to other domains. You'll need to use a middleware like CORSMethodMiddleware to set the Access-Control-Allow-Methods response header.
This middleware will automatically set the Access-Control-Allow-Methods header based on the method matchers you specify for a route. For example, if you use r.Methods(http.MethodGet, http.MethodPut, http.MethodOptions), the middleware will set the header to GET,PUT,OPTIONS.
If you don't specify any methods, you'll still need to include an OPTIONS method matcher for the middleware to work correctly. Without it, the middleware won't be able to set the necessary headers.
Here's a key point to keep in mind: CORSMethodMiddleware only handles the Access-Control-Allow-Methods header, not the other CORS headers like Access-Control-Allow-Origin. You'll still need to use a custom handler to set those headers.
To get started with CORSMethodMiddleware, you'll need to include an OPTIONS method matcher in your route configuration. This will allow the middleware to set the necessary headers and make your API accessible to other domains.
Broaden your view: Golang Rest
[Handler) Get]
In the handler for "Get", you'll need to convert the Recipe object into JSON using the json.Marshal function.
The json.Marshal function is used to do the opposite of parsing JSON into a Recipe object, which is done in the CreateRecipe and UpdateRecipe handlers.
You'll also need to add the status code and body to the HTTP response in the GetRecipe handler.
The status code for a successful request in this case is 200, and the body is the JSON representation of the Recipe object.
To get the Recipe object, you'll need to use the mux.Vars() function with the request as a parameter, which returns a map of parameters matched from the URL pattern defined in the router.
In this case, the parameter is the recipe ID (slug), which is passed as a parameter when the URL is accessed.
The recipe ID (slug) is created by "slugifying" the name of the recipe using the gosimple/slug function.
Recommended read: Golang Source
Testing Handlers
Testing handlers in a Go web application is straightforward, and mux doesn't complicate this any further. Testing handlers is a crucial part of building a robust web application.
You can write table-driven tests to test multiple possible route variables as needed. This approach allows you to cover different scenarios with a single test.
Mux makes it easy to test handlers by allowing you to pass route variables in the request. For example, you can pass variables like path parameters or query parameters.
Testing handlers is a fundamental aspect of web development, and with mux, it's a breeze. With a little practice, you'll be writing tests like a pro in no time.
In the case of routes with variables, you can write tests to cover different variable values. This ensures that your application behaves correctly in all scenarios.
Testing handlers is an essential step in ensuring the reliability and maintainability of your web application. By following best practices and using tools like mux, you can write robust and efficient tests.
Implementing Handlers
Implementing handlers in a Go web application using gorilla/mux is a crucial step in building a robust and efficient API.
To create a URL-friendly recipe name, you need to "slugify" the name using gosimple/slug. This will help you create a unique and readable ID for each recipe.
When implementing handlers, you'll need to define two generic handlers to deal with InternalServer errors and NotFound errors. These handlers should return HTTP code 500 and 404 respectively.
You'll also need to use the mux.Vars() function to retrieve the route variables from the URL pattern defined in the router. This is particularly useful when dealing with routes that have variables.
Here are the five essential steps to implement the handler functions:
- Parse the incoming JSON into a recipes.Recipe using a JSON decoder.
- Use the json.Marshal function to convert the Recipe object into JSON.
- Add the status code and body to the HTTP response in each handler.
- Slugify the recipe name using gosimple/slug.
- Use the mux.Vars() function to retrieve the route variables from the URL pattern.
Methods
Implementing Handlers is a crucial part of building a robust and scalable application.
You can add matchers for HTTP methods using the Methods function. It accepts a sequence of one or more methods to be matched.
To specify multiple methods, you can pass a comma-separated list of methods to the Methods function. For example, "GET", "POST", "PUT".
The Methods function is useful for building simple REST API documentation and for instrumentation against third-party services.
You can retrieve the methods a route matches against using the GetMethods function. This is useful for debugging and testing purposes.
Here's an example of how you can use the Methods function to add a matcher for HTTP methods:
```markdown
Methods adds a matcher for HTTP methods.
It accepts a sequence of one or more methods to be matched, e.g.:
"GET", "POST", "PUT".
```
Explore further: Golang Function Type
Middleware
Middleware is a crucial part of implementing handlers in a web application. It allows you to add behaviors like authentication or logging to your handlers while improving code reuse.
Middleware functions come between the router and a handler function, making it easy to add common functionality to all your handlers. They are defined using a specific type, which typically returns a closure that does something with the http.ResponseWriter and http.Request.
For another approach, see: Golang Add to Map
A very basic middleware can be written to log the URI of the request being handled. Middlewares can be added to a router using Router.Use(), which is a much cleaner and more elegant solution than wrapping middleware around each handler.
Here are some common use cases for middleware:
- Request logging
- Header manipulation
- ResponseWriter hijacking
Middlewares are executed in the order they are added if a match is found, including its subrouters. If a middleware doesn't call next.ServeHTTP() with the corresponding parameters, the handler chain will be stopped.
A more complex authentication middleware can be written to map session tokens to users. Middlewares should write to ResponseWriter if they are going to terminate the request, and they should not write to ResponseWriter if they are not going to terminate it.
A unique perspective: Golang Os Write File
Handler
Implementing handlers is a crucial part of building a web application, and gorilla/mux makes it relatively straightforward.
To set a handler for a route, you can use the Handler function, which sets a handler for the route. This function is available on the Route struct.
When it comes to handling errors, you can define two generic handlers to deal with InternalServer errors (which return HTTP code 500) and NotFound errors (which return HTTP code 404).
These handlers can be used to return a specific HTTP status code and a corresponding error message.
In the case of errors, you can use the HandlerFunc function, which sets a handler function for the route. This function is available on the Route struct.
When it comes to creating a URL-friendly recipe name to use as an ID, you can use the slugify function from the gosimple/slug package.
To create a URL-friendly recipe name, you can use the following code:
slug := slugify(recipeName)
This will create a URL-friendly slug from the recipe name.
In the case of creating a URL-friendly recipe name, you can use the following table to see the different parts of the slugify function:
In the case of handling recipe IDs, you can use the mux.Vars function with the request as a parameter to get the route variables.
This function returns a map of parameters matched from the URL pattern defined in the router.
When it comes to parsing the incoming JSON into a recipe object, you can use the JSON decoder to decode the JSON into a recipe object.
This can be achieved with the following code:
recipe := &recipes.Recipe{}
if err := json.NewDecoder(r.Body).Decode(recipe); err != nil {
return err
}
In the case of converting a recipe object into JSON, you can use the json.Marshal function to marshal the recipe object into JSON.
This can be achieved with the following code:
recipe := &recipes.Recipe{}
if err := json.NewDecoder(r.Body).Decode(recipe); err != nil {
return err
}
if err := json.NewEncoder(w).Encode(recipe); err != nil {
return err
}
In the case of adding a status code and body to the HTTP response, you can use the following code:
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(recipe); err != nil {
return err
}
For your interest: Golang Read Json File
Advanced Topics
Advanced routing with subrouters and middleware is a powerful feature that improves code readability and reusability in larger applications.
Using subrouters allows you to organize your routes in a more logical and maintainable way, making it easier to manage complex applications.
For example, you can create a subrouter for a specific feature, like user management, and reuse that subrouter in multiple parts of your application.
Middleware is another advanced feature that enables you to add functionality to your routes, such as authentication or rate limiting, without modifying the underlying router.
By separating middleware logic from your route definitions, you can keep your code organized and focused on the core functionality of your application.
Discover more: Golang Applications
Router Configuration
The router configuration in gorilla/mux is quite flexible and powerful. You can define the trailing slash behavior for new routes using the StrictSlash method, which defaults to false.
Setting StrictSlash to true will perform a redirect from one path to another, such as from "/path" to "/path/". This is done using a HTTP 301 (Moved Permanently) redirect.
Additional reading: Gcloud Api Using Golang
You can also use middleware to modify the behavior of the redirect. For example, if you're using a non-idempotent method like POST, the subsequent redirect will be made as a GET by most clients.
The StrictSlash method is ignored if a route sets a path prefix using the PathPrefix method. However, any subrouters created from that route will inherit the original StrictSlash setting.
Here's a quick summary of the StrictSlash method:
To append middleware to the router, you can use the Use method. Middleware can be used to intercept or modify requests and responses, and are executed in the order they are applied to the router.
Frequently Asked Questions
Is Gorilla Mux deprecated?
Gorilla Mux was deprecated in December 2022 and is no longer supported, but its popularity among the Go community means a transition period is expected.
Featured Images: pexels.com


