MCPcopy
hub / github.com/go-chi/chi

github.com/go-chi/chi @v5.3.0 sqlite

repository ↗ · DeepWiki ↗ · release v5.3.0 ↗
479 symbols 2,337 edges 78 files 209 documented · 44%
README

chi

[![GoDoc Widget]][GoDoc]

chi is a lightweight, idiomatic and composable router for building Go HTTP services. It's especially good at helping you write large REST API services that are kept maintainable as your project grows and changes. chi is built on the new context package introduced in Go 1.7 to handle signaling, cancelation and request-scoped values across a handler chain.

The focus of the project has been to seek out an elegant and comfortable design for writing REST API servers, written during the development of the Pressly API service that powers our public API service, which in turn powers all of our client-side applications.

The key considerations of chi's design are: project structure, maintainability, standard http handlers (stdlib-only), developer productivity, and deconstructing a large system into many small parts. The core router github.com/go-chi/chi is quite small (less than 1000 LOC), but we've also included some useful/optional subpackages: middleware, render and docgen. We hope you enjoy it too!

Install

go get -u github.com/go-chi/chi/v5

Features

  • Lightweight - cloc'd in ~1000 LOC for the chi router
  • Fast - yes, see benchmarks
  • 100% compatible with net/http - use any http or middleware pkg in the ecosystem that is also compatible with net/http
  • Designed for modular/composable APIs - middlewares, inline middlewares, route groups and sub-router mounting
  • Context control - built on new context package, providing value chaining, cancellations and timeouts
  • Robust - in production at Pressly, Cloudflare, Heroku, 99Designs, and many others (see discussion)
  • Doc generation - docgen auto-generates routing documentation from your source to JSON or Markdown
  • Go.mod support - as of v5, go.mod support (see CHANGELOG)
  • No external dependencies - plain ol' Go stdlib + net/http

Examples

See _examples/ for a variety of examples.

As easy as:

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.Get("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("welcome"))
    })
    http.ListenAndServe(":3000", r)
}

REST Preview:

Here is a little preview of what routing looks like with chi. Also take a look at the generated routing docs in JSON (routes.json) and in Markdown (routes.md).

I highly recommend reading the source of the examples listed above, they will show you all the features of chi and serve as a good form of documentation.

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

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

  // A good base middleware stack
  r.Use(middleware.RequestID)
  r.Use(middleware.ClientIPFromRemoteAddr) // pick one ClientIPFrom* based on your infra, see below
  r.Use(middleware.Logger)
  r.Use(middleware.Recoverer)

  // Set a timeout value on the request context (ctx), that will signal
  // through ctx.Done() that the request has timed out and further
  // processing should be stopped.
  r.Use(middleware.Timeout(60 * time.Second))

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

  // RESTy routes for "articles" resource
  r.Route("/articles", func(r chi.Router) {
    r.With(paginate).Get("/", listArticles)                           // GET /articles
    r.With(paginate).Get("/{month}-{day}-{year}", listArticlesByDate) // GET /articles/01-16-2017

    r.Post("/", createArticle)                                        // POST /articles
    r.Get("/search", searchArticles)                                  // GET /articles/search

    // Regexp url parameters:
    r.Get("/{articleSlug:[a-z-]+}", getArticleBySlug)                // GET /articles/home-is-toronto

    // Subrouters:
    r.Route("/{articleID}", func(r chi.Router) {
      r.Use(ArticleCtx)
      r.Get("/", getArticle)                                          // GET /articles/123
      r.Put("/", updateArticle)                                       // PUT /articles/123
      r.Delete("/", deleteArticle)                                    // DELETE /articles/123
    })
  })

  // Mount the admin sub-router
  r.Mount("/admin", adminRouter())

  http.ListenAndServe(":3333", r)
}

func ArticleCtx(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    articleID := chi.URLParam(r, "articleID")
    article, err := dbGetArticle(articleID)
    if err != nil {
      http.Error(w, http.StatusText(404), 404)
      return
    }
    ctx := context.WithValue(r.Context(), "article", article)
    next.ServeHTTP(w, r.WithContext(ctx))
  })
}

func getArticle(w http.ResponseWriter, r *http.Request) {
  ctx := r.Context()
  article, ok := ctx.Value("article").(*Article)
  if !ok {
    http.Error(w, http.StatusText(422), 422)
    return
  }
  w.Write([]byte(fmt.Sprintf("title:%s", article.Title)))
}

// A completely separate router for administrator routes
func adminRouter() http.Handler {
  r := chi.NewRouter()
  r.Use(AdminOnly)
  r.Get("/", adminIndex)
  r.Get("/accounts", adminListAccounts)
  return r
}

func AdminOnly(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()
    perm, ok := ctx.Value("acl.permission").(YourPermissionType)
    if !ok || !perm.IsAdmin() {
      http.Error(w, http.StatusText(403), 403)
      return
    }
    next.ServeHTTP(w, r)
  })
}

Router interface

chi's router is based on a kind of Patricia Radix trie. The router is fully compatible with net/http.

Built on top of the tree is the Router interface:

// Router consisting of the core routing methods used by chi's Mux,
// using only the standard net/http.
type Router interface {
    http.Handler
    Routes

    // Use appends one or more middlewares onto the Router stack.
    Use(middlewares ...func(http.Handler) http.Handler)

    // With adds inline middlewares for an endpoint handler.
    With(middlewares ...func(http.Handler) http.Handler) Router

    // Group adds a new inline-Router along the current routing
    // path, with a fresh middleware stack for the inline-Router.
    Group(fn func(r Router)) Router

    // Route mounts a sub-Router along a `pattern` string.
    Route(pattern string, fn func(r Router)) Router

    // Mount attaches another http.Handler along ./pattern/*
    Mount(pattern string, h http.Handler)

    // Handle and HandleFunc adds routes for `pattern` that matches
    // all HTTP methods.
    Handle(pattern string, h http.Handler)
    HandleFunc(pattern string, h http.HandlerFunc)

    // Method and MethodFunc adds routes for `pattern` that matches
    // the `method` HTTP method.
    Method(method, pattern string, h http.Handler)
    MethodFunc(method, pattern string, h http.HandlerFunc)

    // HTTP-method routing along `pattern`
    Connect(pattern string, h http.HandlerFunc)
    Delete(pattern string, h http.HandlerFunc)
    Get(pattern string, h http.HandlerFunc)
    Head(pattern string, h http.HandlerFunc)
    Options(pattern string, h http.HandlerFunc)
    Patch(pattern string, h http.HandlerFunc)
    Post(pattern string, h http.HandlerFunc)
    Put(pattern string, h http.HandlerFunc)
    Trace(pattern string, h http.HandlerFunc)

    // NotFound defines a handler to respond whenever a route could
    // not be found.
    NotFound(h http.HandlerFunc)

    // MethodNotAllowed defines a handler to respond whenever a method is
    // not allowed.
    MethodNotAllowed(h http.HandlerFunc)
}

// Routes interface adds two methods for router traversal, which is also
// used by the github.com/go-chi/docgen package to generate documentation for Routers.
type Routes interface {
    // Routes returns the routing tree in an easily traversable structure.
    Routes() []Route

    // Middlewares returns the list of middlewares in use by the router.
    Middlewares() Middlewares

    // Match searches the routing tree for a handler that matches
    // the method/path - similar to routing a http request, but without
    // executing the handler thereafter.
    Match(rctx *Context, method, path string) bool
}

Each routing method accepts a URL pattern and chain of handlers. The URL pattern supports named params (ie. /users/{userID}) and wildcards (ie. /admin/*). URL parameters can be fetched at runtime by calling chi.URLParam(r, "userID") for named parameters and chi.URLParam(r, "*") for a wildcard parameter.

Middleware handlers

chi's middlewares are just stdlib net/http middleware handlers. There is nothing special about them, which means the router and all the tooling is designed to be compatible and friendly with any middleware in the community. This offers much better extensibility and reuse of packages and is at the heart of chi's purpose.

Here is an example of a standard net/http middleware where we assign a context key "user" the value of "123". This middleware sets a hypothetical user identifier on the request context and calls the next handler in the chain.

// HTTP middleware setting a value on the request context
func MyMiddleware(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    // create new context from `r` request context, and assign key `"user"`
    // to value of `"123"`
    ctx := context.WithValue(r.Context(), "user", "123")

    // call the next handler in the chain, passing the response writer and
    // the updated request object with the new context value.
    //
    // note: context.Context values are nested, so any previously set
    // values will be accessible as well, and the new `"user"` key
    // will be accessible from this point forward.
    next.ServeHTTP(w, r.WithContext(ctx))
  })
}

Request handlers

chi uses standard net/http request handlers. This little snippet is an example of a http.Handler func that reads a user identifier from the request context - hypothetically, identifying the user sending an authenticated request, validated+set by a previous middleware handler.

// HTTP handler accessing data from the request context.
func MyRequestHandler(w http.ResponseWriter, r *http.Request) {
  // here we read from the request context and fetch out `"user"` key set in
  // the MyMiddleware example above.
  user := r.Context().Value("user").(string)

  // respond to the client
  w.Write([]byte(fmt.Sprintf("hi %s", user)))
}

URL parameters

chi's router parses and stores URL parameters right onto the request context. Here is an example of how to access URL params in your net/http handlers. And of course, middlewares are able to access the same information.

// HTTP handler accessing the url routing parameters.
func MyRequestHandler(w http.ResponseWriter, r *http.Request) {
  // fetch the url parameter `"userID"` from the request of a matching
  // routing pattern. An example routing pattern could be: /users/{userID}
  userID := chi.URLParam(r, "userID")

  // fetch `"key"` from the request context
  ctx := r.Context()
  key := ctx.Value("key").(string)

  // respond to the client
  w.Write([]byte(fmt.Sprintf("hi %v, %v", userID, key)))
}

Middlewares

chi comes equipped with an optional middleware package, providing a suite of standard net/http middlewares. Please note, any middleware in the ecosystem that is also compatible with net/http can be used with chi's mux.

Core middlewares


chi/middleware Handler description
[AllowContentEncoding] Enforces a whitelist of request Content-Encoding headers
[AllowContentType] Explicit whitelist of accepted request Content-Types
[BasicAuth] Basic HTTP authentication
[Compress] Gzip compression for clients that accept compressed responses
[ContentCharset] Ensure charset for Content-Type request headers
[CleanPath] Clean double slashes from request path
[GetHead] Automatically route undefined HEAD requests to GET handlers
[Heartbeat] Monitoring endpoint to check the servers pulse
[Logger] Logs the start and end of each request with the elapsed processing time
[NoCache] Sets response headers to prevent clients from caching
[Profiler] Easily attach net/http/pprof to your routers
[ClientIPFromHeader] Capture client IP from a trusted single-IP header (X-Real-IP, CF-Connecting-IP, ...)
[ClientIPFromXFF] Capture client IP from X-Forwarded-For, skipping listed trusted CIDR prefixes
[ClientIPFromXFFTrustedProxies] Capture client IP from X-Forwarded-For given a fixed number of trusted proxies
[ClientIPFromRemoteAddr] Capture client IP from the TCP RemoteAddr (server directly on the public internet)
[RealIP] Deprecated — vulner

Extension points exported contracts — how you extend this code

Router (Interface)
Router consisting of the core routing methods used by chi's Mux, using only the standard net/http. [1 implementers]
chi.go
WrapResponseWriter (Interface)
WrapResponseWriter is a proxy around an http.ResponseWriter that allows you to hook into various parts of the response p [1 …
middleware/wrap_writer.go
LogFormatter (Interface)
LogFormatter initiates the beginning of a new LogEntry per request. See DefaultLogFormatter for an example implementatio [1 …
middleware/logger.go
WalkFunc (FuncType)
WalkFunc is the type of the function called for each method and route visited by Walk.
tree.go
EncoderFunc (FuncType)
An EncoderFunc is a function that wraps the provided io.Writer with a streaming compression algorithm and returns it. I
middleware/compress.go
Handler (FuncType)
(no doc)
_examples/custom-handler/main.go
Routes (Interface)
Routes interface adds two methods for router traversal, which is also used by the `docgen` subpackage to generation docu [1 …
chi.go
LogEntry (Interface)
LogEntry records the final log when a request completes. See defaultLogEntry for an example implementation. [1 implementers]
middleware/logger.go

Core symbols most depended-on inside this repo

Get
called by 210
chi.go
Write
called by 197
middleware/logger.go
HandlerFunc
called by 161
chain.go
ServeHTTP
called by 112
mux.go
Use
called by 81
chi.go
InsertRoute
called by 75
tree.go
NewRouter
called by 60
chi.go
Value
called by 56
tree.go

Shape

Function 259
Method 162
Struct 40
Interface 8
TypeAlias 7
FuncType 3

Languages

Go100%

Modules by API surface

mux_test.go45 symbols
mux.go35 symbols
_examples/rest/main.go34 symbols
tree.go33 symbols
middleware/wrap_writer.go30 symbols
chi.go28 symbols
middleware/compress.go24 symbols
middleware/client_ip_test.go21 symbols
middleware/logger.go17 symbols
context.go13 symbols
tree_test.go11 symbols
middleware/route_headers.go11 symbols

Dependencies from manifests, versioned

github.com/ajg/formv1.5.1 · 1×
github.com/go-chi/docgenv1.2.0 · 1×
github.com/go-chi/renderv1.0.3 · 1×

For agents

$ claude mcp add chi \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact