How to Use Gorilla Mux in Go: Simple Routing Guide
To use
gorilla/mux in Go, first import the package, create a new router with mux.NewRouter(), then define routes using methods like HandleFunc. Finally, start the server with http.ListenAndServe passing the router as the handler.Syntax
The basic syntax to use Gorilla Mux involves creating a router, defining routes, and starting the HTTP server.
- mux.NewRouter(): Creates a new router instance.
- router.HandleFunc(path, handler): Registers a route with a path and a handler function.
- http.ListenAndServe(address, router): Starts the server on the given address using the router to handle requests.
go
package main import ( "net/http" "github.com/gorilla/mux" ) func main() { router := mux.NewRouter() // Create router router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, Gorilla Mux!")) }) // Define route http.ListenAndServe(":8080", router) // Start server }
Example
This example shows how to create a simple web server with Gorilla Mux that responds to two routes: the home page and a user page with a dynamic parameter.
go
package main import ( "fmt" "net/http" "github.com/gorilla/mux" ) func homeHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Welcome to the Home Page!")) } func userHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) // Get route variables userID := vars["id"] response := fmt.Sprintf("User ID: %s", userID) w.Write([]byte(response)) } func main() { router := mux.NewRouter() router.HandleFunc("/", homeHandler).Methods("GET") router.HandleFunc("/user/{id}", userHandler).Methods("GET") http.ListenAndServe(":8080", router) }
Output
When you visit http://localhost:8080/ you see: Welcome to the Home Page!
When you visit http://localhost:8080/user/123 you see: User ID: 123
Common Pitfalls
Common mistakes when using Gorilla Mux include:
- Not importing
github.com/gorilla/muxproperly. - Forgetting to call
http.ListenAndServewith the router as the handler. - Not specifying HTTP methods, which can cause unexpected route matches.
- Incorrectly using route variables without
mux.Vars(r).
Always check that your routes are registered before starting the server.
go
package main import ( "net/http" "github.com/gorilla/mux" ) func main() { router := mux.NewRouter() // Wrong: Missing route variable extraction router.HandleFunc("/user/{id}", func(w http.ResponseWriter, r *http.Request) { // This will not get the id correctly w.Write([]byte("User page")) }).Methods("GET") http.ListenAndServe(":8080", router) } // Correct way: // vars := mux.Vars(r) // id := vars["id"] // Use id in response
Quick Reference
Here is a quick summary of Gorilla Mux usage:
| Function | Purpose |
|---|---|
| mux.NewRouter() | Create a new router instance |
| router.HandleFunc(path, handler) | Register a route with a handler function |
| router.HandleFunc(path, handler).Methods("GET") | Register a route for specific HTTP methods |
| mux.Vars(r) | Extract variables from route parameters |
| http.ListenAndServe(address, router) | Start HTTP server with router |
Key Takeaways
Import and create a router with mux.NewRouter() before defining routes.
Use router.HandleFunc to register routes and specify HTTP methods for clarity.
Extract route variables using mux.Vars(r) inside handler functions.
Pass the router to http.ListenAndServe to handle incoming requests.
Check for common mistakes like missing imports or incorrect route variable usage.