~/Golang Routers Explained

Jan 12, 2018


A router in Go is a component that matches incoming HTTP requests to specified handler functions. Basic routing is handled by nethttp, but for more features try gorilla mux or chi.

Basic nethttp example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello world!")
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

With gorilla mux:

1
2
3
4
5
6
7
8
import (
    "github.com/gorilla/mux"
    "net/http"
)

router := mux.NewRouter()
router.HandleFunc("/", handler)
http.ListenAndServe(":8080", router)

For parameterized routing, try:

1
router.HandleFunc("/user/{id}", userHandler)

Choose your router based on project complexity. Standard nethttp is good for simple routes. Use mux or chi for more flexibility.

Tags: [golang] [router] [web]