Claude
Skills
Sign in
Back

chi

Included with Lifetime
$97 forever

Chi lightweight Go HTTP router. Covers routing, middleware, context, and patterns. Use for idiomatic, stdlib-compatible Go APIs. USE WHEN: user mentions "chi", "go-chi", "lightweight go router", "stdlib go router", asks about "chi middleware", "chi router", "chi context", "idiomatic go api", "net/http compatible router", "chi patterns" DO NOT USE FOR: Gin projects - use `gin` instead, Echo projects - use `echo` instead, Fiber projects - use `fiber` instead, non-Go backends

Backend & APIs

What this skill does

# Chi Core Knowledge

> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `chi` for comprehensive documentation.

## Basic Setup

```go
package main

import (
    "net/http"
    "github.com/go-chi/chi/v5"
    "github.com/go-chi/chi/v5/middleware"
)

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

    r.Use(middleware.Logger)
    r.Use(middleware.Recoverer)

    r.Get("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, World!"))
    })

    http.ListenAndServe(":8080", r)
}
```

## Routing

### Basic Routes

```go
r := chi.NewRouter()

r.Get("/users", listUsers)
r.Get("/users/{id}", getUser)
r.Post("/users", createUser)
r.Put("/users/{id}", updateUser)
r.Delete("/users/{id}", deleteUser)

// Method not allowed handler
r.MethodNotAllowed(methodNotAllowedHandler)

// Not found handler
r.NotFound(notFoundHandler)
```

### Path Parameters

```go
r.Get("/users/{userID}", func(w http.ResponseWriter, r *http.Request) {
    userID := chi.URLParam(r, "userID")
    json.NewEncoder(w).Encode(map[string]string{"id": userID})
})

// Regex constraints
r.Get("/articles/{date:\\d{4}-\\d{2}-\\d{2}}", getArticleByDate)

// Catch-all
r.Get("/files/*", serveFiles)
```

### Route Groups

```go
r := chi.NewRouter()

r.Route("/api", func(r chi.Router) {
    r.Route("/v1", func(r chi.Router) {
        r.Get("/users", listUsersV1)
        r.Post("/users", createUserV1)
    })

    r.Route("/v2", func(r chi.Router) {
        r.Get("/users", listUsersV2)
        r.Post("/users", createUserV2)
    })
})
```

### Subrouters

```go
r := chi.NewRouter()

// Mount subrouter
apiRouter := chi.NewRouter()
apiRouter.Get("/users", listUsers)
apiRouter.Post("/users", createUser)

r.Mount("/api/v1", apiRouter)
```

## Context

### Request Context

```go
func getUser(w http.ResponseWriter, r *http.Request) {
    // Path params
    userID := chi.URLParam(r, "userID")

    // Query params
    page := r.URL.Query().Get("page")

    // Headers
    auth := r.Header.Get("Authorization")

    // Context values
    user := r.Context().Value("user").(*User)

    json.NewEncoder(w).Encode(user)
}
```

### Context with Values

```go
func UserContext(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        userID := chi.URLParam(r, "userID")
        user, err := findUser(userID)
        if err != nil {
            http.Error(w, "User not found", http.StatusNotFound)
            return
        }

        ctx := context.WithValue(r.Context(), "user", user)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

r.Route("/users/{userID}", func(r chi.Router) {
    r.Use(UserContext)
    r.Get("/", getUser)
    r.Put("/", updateUser)
})
```

## Middleware

### Built-in Middleware

```go
import "github.com/go-chi/chi/v5/middleware"

r := chi.NewRouter()

r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.Compress(5))
r.Use(middleware.Timeout(60 * time.Second))
r.Use(middleware.Throttle(100))
r.Use(middleware.Heartbeat("/ping"))
```

### Custom Middleware

```go
func TimingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        next.ServeHTTP(w, r)
        duration := time.Since(start)
        log.Printf("%s %s %v", r.Method, r.URL.Path, duration)
    })
}

r.Use(TimingMiddleware)
```

### Authentication Middleware

```go
func AuthMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        auth := r.Header.Get("Authorization")

        if auth == "" {
            http.Error(w, "Unauthorized", http.StatusUnauthorized)
            return
        }

        if !strings.HasPrefix(auth, "Bearer ") {
            http.Error(w, "Invalid token format", http.StatusUnauthorized)
            return
        }

        token := auth[7:]
        user, err := validateToken(token)
        if err != nil {
            http.Error(w, "Invalid token", http.StatusUnauthorized)
            return
        }

        ctx := context.WithValue(r.Context(), "user", user)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

r.Route("/api", func(r chi.Router) {
    r.Use(AuthMiddleware)
    r.Get("/me", getMe)
})

func getMe(w http.ResponseWriter, r *http.Request) {
    user := r.Context().Value("user").(*User)
    json.NewEncoder(w).Encode(user)
}
```

### CORS Middleware

```go
import "github.com/go-chi/cors"

r.Use(cors.Handler(cors.Options{
    AllowedOrigins:   []string{"https://example.com"},
    AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
    AllowedHeaders:   []string{"Accept", "Authorization", "Content-Type"},
    AllowCredentials: true,
    MaxAge:           300,
}))
```

## Response Helpers

### render Package

```go
import "github.com/go-chi/render"

type UserResponse struct {
    ID    string `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

func (u *UserResponse) Render(w http.ResponseWriter, r *http.Request) error {
    return nil
}

func getUser(w http.ResponseWriter, r *http.Request) {
    user := &UserResponse{
        ID:    "1",
        Name:  "Alice",
        Email: "[email protected]",
    }
    render.JSON(w, r, user)
}

// Error response
type ErrResponse struct {
    Err            error  `json:"-"`
    HTTPStatusCode int    `json:"-"`
    StatusText     string `json:"status"`
    ErrorText      string `json:"error,omitempty"`
}

func (e *ErrResponse) Render(w http.ResponseWriter, r *http.Request) error {
    render.Status(r, e.HTTPStatusCode)
    return nil
}

func ErrNotFound(err error) render.Renderer {
    return &ErrResponse{
        Err:            err,
        HTTPStatusCode: http.StatusNotFound,
        StatusText:     "Resource not found",
        ErrorText:      err.Error(),
    }
}
```

### Manual JSON Response

```go
func respond(w http.ResponseWriter, status int, data interface{}) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)
    json.NewEncoder(w).Encode(data)
}

func getUser(w http.ResponseWriter, r *http.Request) {
    user := User{ID: "1", Name: "Alice"}
    respond(w, http.StatusOK, user)
}
```

## Error Handling

```go
type APIError struct {
    StatusCode int    `json:"-"`
    Message    string `json:"message"`
    Details    string `json:"details,omitempty"`
}

func (e *APIError) Error() string {
    return e.Message
}

func errorHandler(w http.ResponseWriter, r *http.Request, err error) {
    var apiErr *APIError
    if errors.As(err, &apiErr) {
        respond(w, apiErr.StatusCode, apiErr)
        return
    }

    respond(w, http.StatusInternalServerError, map[string]string{
        "message": "Internal server error",
    })
}

func getUser(w http.ResponseWriter, r *http.Request) {
    userID := chi.URLParam(r, "userID")
    user, err := findUser(userID)
    if err != nil {
        errorHandler(w, r, &APIError{
            StatusCode: http.StatusNotFound,
            Message:    "User not found",
        })
        return
    }
    respond(w, http.StatusOK, user)
}
```

## Patterns

### Resource Pattern

```go
type UsersResource struct {
    db *sql.DB
}

func (rs UsersResource) Routes() chi.Router {
    r := chi.NewRouter()

    r.Get("/", rs.List)
    r.Post("/", rs.Create)

    r.Route("/{id}", func(r chi.Router) {
        r.Use(rs.UserCtx)
        r.Get("/", rs.Get)
        r.Put("/", rs.Update)
        r.Delete("/", rs.Delete)
    })

    return r
}

func (rs UsersResource) UserCtx(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        id := chi.URLParam(r, "id")
        user, err := rs.db.FindUser(id)
        if err != nil {
            http.Error(w, "User not found", http.StatusNotFound)
            return
        }
        ctx := context.WithValue(r.Context(), "user", user)
        next.S

Related in Backend & APIs