chi

package
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 11, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package chi adapts api/rest route handles to github.com/go-chi/chi/v5 routers.

Each [RouteHandle] from api/rest becomes an http.HandlerFunc via Handler. Register wires it directly onto a chi.Router using the route's method and path.

Chi uses {param} placeholders identical to the go-codex path template syntax, so no path translation is needed. Path variables are extracted via chi.URLParam.

Typical usage:

b := rest.NewBuilder(rest.Info{Title: "User API", Version: "1.0.0"})
createUser, _ := rest.NewRoute[CreateReq, User]("POST", "/users", ...).Register(b)

r := chi.NewRouter()
chiadapter.Register(r, createUser, func(ctx context.Context, req CreateReq) (User, error) {
    rr, _ := chiadapter.RequestFromContext(ctx)
    id := chi.URLParam(rr, "id")
    return svc.CreateUser(ctx, req)
}, chiadapter.Options{})
http.ListenAndServe(":8080", r)

Error responses use the JSON body {"error":"<message>"} by default: 400 for decode/validation failures, 500 for handler or encode errors. Override via Options.ErrorHandler.

For body-less methods (GET, HEAD, DELETE) the handler function is called with the zero value of Req. Access path and query parameters through RequestFromContext and chi.URLParam.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Handler

func Handler[Req, Resp any](handle *rest.RouteHandle[Req, Resp], fn HandlerFunc[Req, Resp], opts Options) http.HandlerFunc

Handler wraps a rest.RouteHandle and a HandlerFunc into an http.HandlerFunc suitable for use with a chi.Router.

func Register

func Register[Req, Resp any](r gochi.Router, handle *rest.RouteHandle[Req, Resp], fn HandlerFunc[Req, Resp], opts Options)

Register registers the route on r using its method and path from the route descriptor. Chi uses the same {param} placeholder syntax as go-codex path templates, so no translation is needed.

func RegisterSSE

func RegisterSSE[Req, Event any](r gochi.Router, handle *rest.SSERouteHandle[Req, Event], fn SSEHandlerFunc[Req, Event], opts Options)

RegisterSSE wires an rest.SSERouteHandle onto a chi router as a GET SSE endpoint.

func RequestFromContext

func RequestFromContext(ctx context.Context) (*http.Request, bool)

RequestFromContext retrieves the *http.Request stored in ctx by Handler. Returns false if the context was not created by this package.

func ResponseHeadersFromContext

func ResponseHeadersFromContext(ctx context.Context) (http.Header, bool)

ResponseHeadersFromContext retrieves response headers previously stored by WithResponseHeaders. Returns false if no headers were set.

func SSEHandler

func SSEHandler[Req, Event any](handle *rest.SSERouteHandle[Req, Event], fn SSEHandlerFunc[Req, Event], opts Options) http.HandlerFunc

SSEHandler wraps an rest.SSERouteHandle and a user-supplied SSEHandlerFunc into an http.HandlerFunc that streams Server-Sent Events.

The handler sets Content-Type: text/event-stream, Cache-Control: no-cache, and Connection: keep-alive, then calls fn. The send func provided to fn validates the event via the codec, encodes it as JSON, writes "data: <json>\n\n" to the response, and flushes. If the event fails validation, send returns an error without writing anything.

fn should honour ctx.Done() for clean client-disconnect handling.

func SetCookie

func SetCookie(w http.ResponseWriter, name, value string, opts CookieOptions) error

SetCookie writes a Set-Cookie header on w with secure defaults: Secure, HttpOnly, SameSite=Strict, Path="/".

If CookieOptions.Codec is non-nil, value is validated first. A validation failure returns rest.CookieParamError without writing any header.

func WithResponseCookies

func WithResponseCookies(ctx context.Context, cookies ...PendingCookie)

WithResponseCookies deposits one or more PendingCookie values into ctx. Handler validates their values against the route's [ResponseCookieParam] codecs and writes Set-Cookie headers on success.

func WithResponseHeaders

func WithResponseHeaders(ctx context.Context, h http.Header)

WithResponseHeaders copies the key-value pairs from h into the response header map stored in ctx (pre-allocated by Handler before calling the HandlerFunc). Call this inside a HandlerFunc to emit response headers such as Location, ETag, or custom headers without direct access to http.ResponseWriter.

Types

type CookieOptions

type CookieOptions struct {
	// Path is the cookie path. Defaults to "/" when empty.
	Path string

	// Domain scopes the cookie to a specific host. Defaults to the current host.
	Domain string

	// MaxAge is the cookie lifetime in seconds.
	// 0 means session cookie (deleted when browser closes).
	// Negative means delete the cookie immediately.
	MaxAge int

	// SameSite controls the cross-site request behaviour.
	// Defaults to [http.SameSiteStrictMode] when zero.
	SameSite http.SameSite

	// Insecure, when true, omits the Secure attribute.
	// Use only for non-TLS environments such as localhost development.
	Insecure bool

	// AllowJS, when true, omits the HttpOnly attribute.
	AllowJS bool

	// Codec, when non-nil, validates value before the Set-Cookie header is written.
	// Set via [CookieOptions.WithCodec] to avoid address-of boilerplate.
	Codec *codex.Codec[string]
}

CookieOptions configures the security attributes and optional value validation applied by SetCookie.

Safe defaults: Secure=true, HttpOnly=true, SameSite=Strict, Path="/". Use the opt-in fields to relax specific attributes for legitimate use cases.

func (CookieOptions) WithCodec

func (o CookieOptions) WithCodec(c codex.Codec[string]) CookieOptions

WithCodec sets the validation codec and returns the updated CookieOptions. Avoids the temporary-variable + address-of pattern required when setting Codec inline:

err := chiadapter.SetCookie(w, "session_token", token,
    chiadapter.CookieOptions{MaxAge: 3600}.WithCodec(sessionCodec))

type HandlerFunc

type HandlerFunc[Req, Resp any] func(ctx context.Context, req Req) (Resp, error)

HandlerFunc is the typed application handler called by Handler. ctx is the request context. req is the decoded request value; for body-less methods it is the zero value of Req. Use RequestFromContext to access the underlying *http.Request for path parameters and headers. Chi path params are available via chi.URLParam(r, "name").

type Options

type Options struct {
	// ErrorHandler, when non-nil, is called instead of the default JSON error
	// envelope when a request fails. status is the suggested HTTP status code.
	// Implementations must write the response header and body.
	ErrorHandler func(w http.ResponseWriter, r *http.Request, status int, err error)

	// Observer, when non-nil, receives per-request lifecycle events.
	// Defaults to [stats.NoopObserver] when nil.
	Observer stats.Observer

	// MaxBodyBytes limits the number of bytes read from the request body.
	// Zero means the default (1 MiB).
	MaxBodyBytes int64

	// ContentType is the expected Content-Type for body-bearing methods.
	// Defaults to "application/json".
	ContentType string

	// MultiValueQueryParams, when true, uses [rest.RouteHandle.ValidateQueryMulti].
	MultiValueQueryParams bool

	// SecurityFunc, when non-nil, is called for routes that declare a non-nil
	// Security field (via [rest.RouteMeta.Security] or global security), after
	// parameter validation but before the handler fn.
	//
	// Return a non-nil error to reject the request with 401 Unauthorized.
	// reqs contains the route's declared security requirements (scheme names +
	// scopes). The adapter has already extracted and codec-validated the credential
	// from the request before calling SecurityFunc.
	//
	// Example — JWT bearer verification:
	//
	//	opts.SecurityFunc = func(ctx context.Context, r *http.Request, reqs []route.SecurityRequirement) error {
	//	    token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
	//	    return jwtlib.VerifyScopes(token, reqs)
	//	}
	SecurityFunc func(ctx context.Context, r *http.Request, reqs []route.SecurityRequirement) error
}

Options configures the behaviour of Handler and Register.

type PendingCookie

type PendingCookie struct {
	Name  string
	Value string
	Opts  CookieOptions
}

PendingCookie is a cookie queued to be validated and written as a Set-Cookie response header by Handler.

func ResponseCookiesFromContext

func ResponseCookiesFromContext(ctx context.Context) ([]PendingCookie, bool)

ResponseCookiesFromContext retrieves pending cookies previously stored by WithResponseCookies.

type SSEHandlerFunc

type SSEHandlerFunc[Req, Event any] func(ctx context.Context, req Req, send func(Event) error) error

SSEHandlerFunc is the typed application handler called by SSEHandler. ctx is the request context (cancelled when the client disconnects). req is the decoded request (zero value for body-less GET requests). send encodes, validates, and writes one SSE event; it returns an error if the event fails codec validation or if the underlying write fails.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL