← Project templates

WEB AND APIS · IN THE APP NOW

chi router

Routes grouped the chi way: middleware on the router, a /users subtree declared with r.Route, and a {name} parameter read with chi.URLParam.

Downloads github.com/go-chi/chi/v5 on first build (about 60 KB)

Open it in the browser Playground →

What it is

chi is not bundled with the app. The project's go.mod requires github.com/go-chi/chi/v5 v5.5.0 with its go.sum checksums, and the first build downloads it from the Go module proxy, about 60 KB. Later builds use the downloaded copy.

A chi router is an http.Handler, so main plays four GET requests through it with httptest, including a path chi answers with 404.

Every template's Go program was compiled for GOOS=wasip1 GOARCH=wasm with Go 1.27, then run, vetted and tested before it was added to the app.

Files

text
chi-api/
├── go.mod
├── go.sum
└── main.go

The code

main.go

go
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

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

func newRouter() http.Handler {
	r := chi.NewRouter()
	r.Use(middleware.Recoverer)
	r.Use(middleware.SetHeader("Content-Type", "text/plain; charset=utf-8"))

	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "welcome")
	})
	r.Route("/users", func(r chi.Router) {
		r.Get("/", func(w http.ResponseWriter, r *http.Request) {
			fmt.Fprintln(w, "ada, grace, ken")
		})
		r.Get("/{name}", func(w http.ResponseWriter, r *http.Request) {
			fmt.Fprintf(w, "hello, %s\n", chi.URLParam(r, "name"))
		})
	})
	return r
}

// chi is downloaded on the first build (about 60 KB). The sandbox has no
// sockets, so requests are played in-process; on a server use
// http.ListenAndServe(":8080", newRouter()).
func main() {
	router := newRouter()
	for _, path := range []string{"/", "/users", "/users/gopher", "/missing"} {
		recorder := httptest.NewRecorder()
		router.ServeHTTP(recorder, httptest.NewRequest("GET", path, nil))
		fmt.Printf("GET %-13s %d %s\n", path, recorder.Code, strings.TrimSpace(recorder.Body.String()))
	}
}

What you learn

  • Add middleware with r.Use: middleware.Recoverer and middleware.SetHeader.
  • Group routes under a prefix with r.Route.
  • Declare a {name} parameter and read it with chi.URLParam.
  • Treat the router as a plain http.Handler for httptest and http.ListenAndServe alike.
  • Pin a third-party module with go.mod and go.sum.

Run it on a server

Replace the request loop in main with http.ListenAndServe, as the comment in main.go says, then import log and drop the imports main no longer uses.

go
func main() {
	log.Fatal(http.ListenAndServe(":8080", newRouter()))
}
bash
go run .
curl localhost:8080/users/gopher

Related: http.Handler is one method, like Reader · Go services