Gorilla mux in Go: routing, path variables, subrouters, and middleware

Gorilla mux tutorial for gorilla mux and golang gorilla mux: install github.com/gorilla/mux, gorilla mux example with Methods and path vars, subrouters, middleware with r.Use, mux gorilla naming, and gorilla mux vs gin vs net/http.

Published

Updated

Read time 3 min read

Reviewed byDeepak Prasad

Gorilla mux in Go: routing, path variables, subrouters, and middleware

Gorilla mux (github.com/gorilla/mux) is the router most people mean when they search gorilla mux, golang gorilla mux, go gorilla mux, mux gorilla, or golang mux. This gorilla mux tutorial gives a practical gorilla mux example: install the module, register routes with HTTP methods, read path variables, attach middleware, and optionally compare gorilla mux vs gin. For plain net/http, see HTTP in Go; for a framework-style alternative, see Gin or Chi.

Tested with Go 1.24 on Linux. Examples use modules and run on your machine (go run .), not the browser-only Playground.


Install github.com/gorilla/mux

From a module (packaging, modules list):

text
go mod init example.com/demo
go get github.com/gorilla/mux

Import path github.com/gorilla/mux (docs often shorten that to gorilla/mux for the same module).


Router, methods, and path variables

mux.NewRouter() returns an *mux.Router that you pass to http.ListenAndServe(addr, r). Use .Methods(...) so the same path can differ by verb. Path vars use {name}; optional regex uses {name:pattern}.

go
package main

import (
	"log"
	"net/http"

	"github.com/gorilla/mux"
)

func health(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("ok"))
}

func user(w http.ResponseWriter, r *http.Request) {
	id := mux.Vars(r)["id"]
	w.Write([]byte("user:" + id))
}

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/health", health).Methods(http.MethodGet)
	r.HandleFunc("/users/{id:[0-9]+}", user).Methods(http.MethodGet)

	log.Fatal(http.ListenAndServe(":8080", r))
}

Run with go run . and hit GET /health and GET /users/42 (for example with curl); you should see ok and user:42.


Subrouters and prefixes

Group routes with PathPrefix + Subrouter() so shared paths and middleware stay tidy—common for /api/v1 style APIs.

go
api := r.PathPrefix("/api/v1").Subrouter()
api.HandleFunc("/items", listItems).Methods(http.MethodGet)

Implement listItems like any other http.HandlerFunc.


Middleware with r.Use

Use chains http.Handler wrappers around matched routes (subrouters can have their own Use).

go
package main

import (
	"log"
	"net/http"

	"github.com/gorilla/mux"
)

func logging(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Printf("%s %s", r.Method, r.URL.Path)
		next.ServeHTTP(w, r)
	})
}

func main() {
	r := mux.NewRouter()
	r.Use(logging)
	r.HandleFunc("/x", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("x"))
	}).Methods(http.MethodGet)
	log.Fatal(http.ListenAndServe(":8080", r))
}

Gorilla mux vs Gin (and stdlib)

Gorilla mux vs gin is mostly library vs framework: mux only routes and dispatches to http.HandlerFunc; Gin gives gin.Context, binding, JSON helpers, and a larger middleware catalog at the cost of locking into Gin’s types. net/http.ServeMux in modern Go adds method-based patterns for simpler apps—use mux when you need regex path vars, host constraints, or nested subrouters without adopting a full framework.


Summary

This gorilla mux tutorial covered installing github.com/gorilla/mux, a minimal go gorilla mux server with method-aware routes and mux.Vars, grouping with subrouters, and r.Use middleware—enough to ship a small REST surface. Searches for gorilla mux golang or gorilla mux example map to the same primitives; pair routing with your own persistence layer per project needs. Official repo: github.com/gorilla/mux. For broader web context, see web server and web frameworks.


References


Frequently Asked Questions

1. What is gorilla/mux in Go?

It is a popular third-party router that implements http.Handler, layering path matching, methods, host rules, and subrouters on top of net/http.

2. How is gorilla mux vs gin different?

Mux is a focused router you compose with plain net/http handlers; Gin is a full web framework with its own context, binding helpers, and middleware ecosystem—often faster to scaffold APIs in Gin, more explicit wiring with mux.

3. How do I read path parameters in gorilla mux?

Use mux.Vars(r) after defining placeholders such as {id} or regex constraints like {id:[0-9]+} in HandleFunc paths.

4. Should I still use go get for gorilla mux?

In a module, add the import and run go get github.com/gorilla/mux or let go mod tidy fetch it; pin versions in go.mod for production.

5. Is golang mux only gorilla?

People say golang mux for this package often; other routers include chi and the stdlib ServeMux in Go 1.22+—compare goals before choosing.
Antony Shikubu

Systems Integration Engineer

Highly skilled software developer with expertise in Python, Golang, and AWS cloud services.