chi
БесплатноБез исполняемых скриптовНе проверенChi is a lightweight Go HTTP router built on net/http, with composable middleware, route groups, URL parameters and sub-routers. Use when building a REST API…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
Chi - Lightweight Go HTTP Router
Overview
Chi (github.com/go-chi/chi/v5, current release v5.5.0) is a small router that keeps the standard library's http.Handler and http.HandlerFunc types, so any net/http middleware works unchanged. It adds method routing (r.Get, r.Post), URL parameters (/{userID}, regexp /{slug:[a-z-]+}), nested routes with scoped middleware (r.Route, r.Group, r.With) and mounted sub-routers (r.Mount). It has no dependencies beyond the standard library. CORS lives in a separate module, github.com/go-chi/cors.
Instructions
Install:
go get github.com/go-chi/chi/v5(addgithub.com/go-chi/corsonly if a browser calls the API from another origin). The import path always ends in/v5.Create the router with
chi.NewRouter()and register middleware withr.Use(...)before any route; chi panics ifUseis called after routes exist on the same router.Put the middleware in this order:
RequestID, a client-IP middleware,Logger,Recoverer,Timeout, then CORS and auth.Get the client IP with exactly one of the
ClientIPFrom*middlewares and read it withmiddleware.GetClientIP(ctx). Do not usemiddleware.RealIP: v5.5 marks it deprecated because it trusts spoofable headers and rewritesr.RemoteAddr.Deployment Middleware Server is directly on the internet middleware.ClientIPFromRemoteAddrBehind nginx, Cloudflare or another proxy that always overwrites one header middleware.ClientIPFromHeader("CF-Connecting-IP")Behind proxies whose address ranges you know middleware.ClientIPFromXFF("10.0.0.0/8")Fixed number of proxies with changing addresses middleware.ClientIPFromXFFTrustedProxies(2)Group routes with
r.Route("/api", func(r chi.Router) {...}); middleware added inside applies only to that subtree. User.Group(func(r chi.Router) {...})for middleware without a path prefix, andr.With(mw).Get(...)for a single route.Read parameters with
chi.URLParam(r, "userID"). To load a resource once for several routes, write a middleware that looks it up, stores it withcontext.WithValueunder a private key type, and attach it withr.Useinside the/{userID}route.middleware.Timeout(d)only cancels the request context and answers 504; handlers and database calls must watchr.Context()for it to take effect.Mount independent routers with
r.Mount("/admin", adminRouter()). Customise 404 and 405 withr.NotFound(h)andr.MethodNotAllowed(h).Test handlers without a network: call
router.ServeHTTP(rec, req)withhttptest.NewRecorder().
Examples
Example 1: A small users API with auth and a context loader
User request: "Set up a chi API with a health check, a protected /api/users group, and a middleware that loads the user once per request."
This main.go was compiled and tested with Go 1.27.3 and chi v5.5.0 (go mod init shopwave && go get github.com/go-chi/chi/v5 github.com/go-chi/cors).
package main
import (
"context"
"crypto/subtle"
"encoding/json"
"errors"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
type store struct {
mu sync.RWMutex
users map[int]User
next int
}
func (s *store) find(id int) (User, error) {
s.mu.RLock()
defer s.mu.RUnlock()
u, ok := s.users[id]
if !ok {
return User{}, errors.New("not found")
}
return u, nil
}
func (s *store) add(u User) User {
s.mu.Lock()
defer s.mu.Unlock()
s.next++
u.ID = s.next
s.users[u.ID] = u
return u
}
type ctxKey string
const userKey ctxKey = "user"
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(v)
}
func newRouter(db *store, apiKey string) http.Handler {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.ClientIPFromRemoteAddr) // direct exposure; behind a proxy pick another ClientIPFrom*
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(middleware.Timeout(30 * time.Second))
r.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"https://app.shopwave.io"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
AllowedHeaders: []string{"Authorization", "Content-Type"},
MaxAge: 300,
}))
r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok", "client": middleware.GetClientIP(r.Context())})
})
r.Route("/api", func(r chi.Router) {
r.Use(requireKey(apiKey))
r.Route("/users", func(r chi.Router) {
r.Post("/", func(w http.ResponseWriter, r *http.Request) {
var in User
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&in); err != nil || in.Email == "" {
writ
Установить chi в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл chi?
Chi is a lightweight Go HTTP router built on net/http, with composable middleware, route groups, URL parameters and sub-routers. Use when building a REST API or web service in Go, adding middleware (logging, timeouts, auth, CORS, client IP), nesting routes under /api, loading a resource into the request context, or migrating from gorilla/mux or the standard ServeMux.
Как установить скилл chi?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл chi запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic