Chi — Lightweight Go HTTP Router
You are an expert in Chi, the lightweight, idiomatic Go HTTP router built on net/http. You help developers build composable HTTP services using Chi's middleware stack, route groups, URL parameters, sub-routers, and context-based request scoping — providing Express-like ergonomics while staying 100% compatible with Go's standard library.
Core Capabilities
Router and Routes
package main
import (
"encoding/json"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
)
func main() {
r := chi.NewRouter()
// Built-in middleware
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Timeout(30 * time.Second))
r.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"https://app.example.com"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
}))
// Public routes
r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
})
// Protected routes
r.Route("/api", func(r chi.Router) {
r.Use(authMiddleware)
r.Route("/users", func(r chi.Router) {
r.Get("/", listUsers)
r.Post("/", createUser)
r.Route("/{userID}", func(r chi.Router) {
r.Use(userCtx) // Load user into context
r.Get("/", getUser)
r.Put("/", updateUser)
r.Delete("/", deleteUser)
r.Get("/posts", getUserPosts)
})
})
})
http.ListenAndServe(":3000", r)
}
// Context middleware — load resource once, use in all sub-routes
func userCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
userID := chi.URLParam(r, "userID")
user, err := db.FindUser(userID)
if err != nil {
http.Error(w, "user not found", 404)
return
}
ctx := context.WithValue(r.Context(), "user", user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func getUser(w http.ResponseWriter, r *http.Request) {
user := r.Context().Value("user").(*User)
json.NewEncoder(w).Encode(user)
}
func listUsers(w http.ResponseWriter, r *http.Request) {
page := r.URL.Query().Get("page")
users, _ := db.ListUsers(page)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(users)
}
Installation
go get -u github.com/go-chi/chi/v5
Best Practices
- stdlib compatible — Chi handlers are
http.HandlerFunc; use any net/http middleware without adapters
- Route groups — Use
r.Route("/prefix", func(r chi.Router) {...}) for scoped middleware and routes
- Context middleware — Load resources in middleware, share via
context.WithValue; DRY across sub-routes
- URL params — Use
chi.URLParam(r, "id") to extract route parameters; type-safe, explicit
- Middleware ordering — Logger first, Recoverer second; auth before route-specific middleware
- Sub-routers — Mount independent routers:
r.Mount("/admin", adminRouter()); clean separation
- Timeouts — Use
middleware.Timeout to prevent slow handlers from blocking; returns 504 on timeout
- No magic — Chi doesn't do dependency injection or auto-binding; explicit is better than implicit in Go
1---2name: chi3description: >-4 You are an expert in Chi, the lightweight, idiomatic Go HTTP router built5 on `net/http`. You help developers build composable HTTP services using6 Chi's middleware stack, route groups, URL parameters, sub-routers, and7 context-based request scoping — providing Express-like ergonomics while8 staying 100% compatible with Go's standard library.9license: Apache-2.010compatibility: ''11metadata:12 source: https://skillmd.com/skills/eliferjunior/chi13 author: terminal-skills14 version: 1.0.015 category: Backend Development16 tags:17 - go18 - router19 - http20 - middleware21 - lightweight22 - stdlib-compatible23---2425# Chi — Lightweight Go HTTP Router2627You are an expert in Chi, the lightweight, idiomatic Go HTTP router built on `net/http`. You help developers build composable HTTP services using Chi's middleware stack, route groups, URL parameters, sub-routers, and context-based request scoping — providing Express-like ergonomics while staying 100% compatible with Go's standard library.2829## Core Capabilities3031### Router and Routes3233```go34package main3536import (37 "encoding/json"38 "net/http"39 "github.com/go-chi/chi/v5"40 "github.com/go-chi/chi/v5/middleware"41 "github.com/go-chi/cors"42)4344func main() {45 r := chi.NewRouter()4647 // Built-in middleware48 r.Use(middleware.Logger)49 r.Use(middleware.Recoverer)50 r.Use(middleware.RequestID)51 r.Use(middleware.RealIP)52 r.Use(middleware.Timeout(30 * time.Second))53 r.Use(cors.Handler(cors.Options{54 AllowedOrigins: []string{"https://app.example.com"},55 AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},56 }))5758 // Public routes59 r.Get("/health", func(w http.ResponseWriter, r *http.Request) {60 json.NewEncoder(w).Encode(map[string]string{"status": "ok"})61 })6263 // Protected routes64 r.Route("/api", func(r chi.Router) {65 r.Use(authMiddleware)6667 r.Route("/users", func(r chi.Router) {68 r.Get("/", listUsers)69 r.Post("/", createUser)7071 r.Route("/{userID}", func(r chi.Router) {72 r.Use(userCtx) // Load user into context73 r.Get("/", getUser)74 r.Put("/", updateUser)75 r.Delete("/", deleteUser)76 r.Get("/posts", getUserPosts)77 })78 })79 })8081 http.ListenAndServe(":3000", r)82}8384// Context middleware — load resource once, use in all sub-routes85func userCtx(next http.Handler) http.Handler {86 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {87 userID := chi.URLParam(r, "userID")88 user, err := db.FindUser(userID)89 if err != nil {90 http.Error(w, "user not found", 404)91 return92 }93 ctx := context.WithValue(r.Context(), "user", user)94 next.ServeHTTP(w, r.WithContext(ctx))95 })96}9798func getUser(w http.ResponseWriter, r *http.Request) {99 user := r.Context().Value("user").(*User)100 json.NewEncoder(w).Encode(user)101}102103func listUsers(w http.ResponseWriter, r *http.Request) {104 page := r.URL.Query().Get("page")105 users, _ := db.ListUsers(page)106 w.Header().Set("Content-Type", "application/json")107 json.NewEncoder(w).Encode(users)108}109```110111## Installation112113```bash114go get -u github.com/go-chi/chi/v5115```116117## Best Practices1181191. **stdlib compatible** — Chi handlers are `http.HandlerFunc`; use any `net/http` middleware without adapters1202. **Route groups** — Use `r.Route("/prefix", func(r chi.Router) {...})` for scoped middleware and routes1213. **Context middleware** — Load resources in middleware, share via `context.WithValue`; DRY across sub-routes1224. **URL params** — Use `chi.URLParam(r, "id")` to extract route parameters; type-safe, explicit1235. **Middleware ordering** — Logger first, Recoverer second; auth before route-specific middleware1246. **Sub-routers** — Mount independent routers: `r.Mount("/admin", adminRouter())`; clean separation1257. **Timeouts** — Use `middleware.Timeout` to prevent slow handlers from blocking; returns 504 on timeout1268. **No magic** — Chi doesn't do dependency injection or auto-binding; explicit is better than implicit in Go