Go Chi HTTP router

Posted on Aug 9, 2020

Using the built-in ServeMux router is a good way to get started with the net/http package and the Handler interface, but for something more serious you might want to look into some of the more advanced routers that are available. For example, Chi.

Here we’ve modified the Hello World example to use Chi and accept a URL parameter called name.

package main

import (
    "fmt"
    "net/http"

    "github.com/go-chi/chi"
)

func main() {
    router := chi.NewRouter()

    router.Get("/hello/{name}", func(w http.ResponseWriter, r *http.Request) {
        name := chi.URLParam(r, "name")

        w.Write([]byte(fmt.Sprintf("Hello %s!", name)))
    })

    http.ListenAndServe("localhost:3000", router)
}

Chi makes it easy nest routes with a common pattern prefix, using the Route() method. Here we introduce goodbye handler and group it together with the hello handler under the "/greeting" pattern.

package main

import (
    "fmt"
    "net/http"

    "github.com/go-chi/chi"
)

func main() {
    router := chi.NewRouter()

    router.Route("/greeting", func(r chi.Router) {
        r.Get("/hello/{name}", func(w http.ResponseWriter, r *http.Request) {
            name := chi.URLParam(r, "name")
    
            w.Write([]byte(fmt.Sprintf("Hello %s!", name)))
        })
    
        r.Get("/goodbye/{name}", func(w http.ResponseWriter, r *http.Request) {
            name := chi.URLParam(r, "name")
    
            w.Write([]byte(fmt.Sprintf("Goodbye %s...", name)))
        })
    })
    
    http.ListenAndServe("localhost:3000", router)
}

Instead of defining the routes and handler in this way, it can be useful to split them up in separate routers and compose them using the Mount() method.

package main

import (
    "fmt"
    "net/http"

    "github.com/go-chi/chi"
)

func NewGreetingsRouter() *chi.Mux {
    router := chi.NewRouter()

    router.Get("/hello/{name}", func(w http.ResponseWriter, r *http.Request) {
        name := chi.URLParam(r, "name")

        w.Write([]byte(fmt.Sprintf("Hello %s!", name)))
    })

    router.Get("/goodbye/{name}", func(w http.ResponseWriter, r *http.Request) {
        name := chi.URLParam(r, "name")

        w.Write([]byte(fmt.Sprintf("Goodbye %s...", name)))
    })

    return router
}

func main() {
    router := chi.NewRouter()
    router.Mount("/greeting", NewGreetingsRouter())

    http.ListenAndServe("localhost:3000", router)
}

comments powered by Disqus