Documentation
¶
Overview ¶
Package server provides the HTTP server, router, middleware, and auth primitives.
Index ¶
- Variables
- func AuthMiddleware(extract ClaimsExtractor, logger Logger) func(http.Handler) http.Handler
- func ContextWithOrgID(ctx context.Context, orgID string) context.Context
- func ContextWithScopes(ctx context.Context, scopes []string) context.Context
- func ContextWithUserID(ctx context.Context, userID string) context.Context
- func OrgIDFromContext(ctx context.Context) (string, bool)
- func Param(r *http.Request, key string) string
- func ReadJSON(r *http.Request, v any) error
- func ReadRawJSON(r *http.Request) (json.RawMessage, error)
- func Register(r HandleRouter, routes []Route)
- func RoutePattern(r *http.Request) string
- func ScopesFromContext(ctx context.Context) []string
- func SlogMiddleware(cfg SlogConfig, logger Logger) func(http.Handler) http.Handler
- func UserIDFromContext(ctx context.Context) (string, bool)
- func Wildcard(r *http.Request) string
- func WriteBadRequest(w http.ResponseWriter, err error)
- func WriteError(w http.ResponseWriter, status int, err error)
- func WriteJSON(w http.ResponseWriter, status int, v any)
- type Action
- type Authorizer
- type Claims
- type ClaimsExtractor
- type Config
- type ErrorResponse
- type HandleRouter
- type Logger
- type Option
- type Route
- type Router
- func (r *Router) Delete(p string, h http.HandlerFunc)
- func (r *Router) Get(p string, h http.HandlerFunc)
- func (r *Router) Group(prefix string, fn func(*Router))
- func (r *Router) Handle(method, pattern string, h http.Handler)
- func (r *Router) LogRoutes(logger Logger)
- func (r *Router) Patch(p string, h http.HandlerFunc)
- func (r *Router) Post(p string, h http.HandlerFunc)
- func (r *Router) Put(p string, h http.HandlerFunc)
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) Use(mw ...func(http.Handler) http.Handler)
- func (r *Router) With(mw ...func(http.Handler) http.Handler) *Router
- type Server
- type SlogConfig
Constants ¶
This section is empty.
Variables ¶
ErrUnauthorized is returned by Authorizer.Authorize when the caller lacks permission. Map to HTTP 403 in handlers.
Functions ¶
func AuthMiddleware ¶
AuthMiddleware extracts the Bearer token, runs extract to parse it into Claims, injects OrgID/UserID/Scopes into the request context, and aborts with HTTP 401 on missing/invalid header or extractor failure.
func ContextWithOrgID ¶
ContextWithOrgID returns a copy of ctx carrying the org ID.
func ContextWithScopes ¶
ContextWithScopes returns a copy of ctx carrying the caller's scopes.
func ContextWithUserID ¶
ContextWithUserID returns a copy of ctx carrying the user ID.
func OrgIDFromContext ¶
OrgIDFromContext reads the org ID set by ContextWithOrgID. ok is false if unset.
func Param ¶
Param returns the named path parameter from the matched route, or "" if absent. Handlers should use this instead of importing chi directly.
func ReadRawJSON ¶
func ReadRawJSON(r *http.Request) (json.RawMessage, error)
ReadRawJSON returns the request body as a json.RawMessage after validating it is well-formed JSON.
func RoutePattern ¶
RoutePattern returns the matched route pattern (e.g. "/items/{id}"), useful for metrics and structured logging. Returns "" when called outside a matched route.
func ScopesFromContext ¶
ScopesFromContext reads the scopes set by ContextWithScopes. Returns nil if unset.
func SlogMiddleware ¶
SlogMiddleware logs method, url and duration for every request, plus optionally the request and response bodies when the config opts in.
func UserIDFromContext ¶
UserIDFromContext reads the user ID set by ContextWithUserID. ok is false if unset.
func Wildcard ¶
Wildcard returns the value matched by a trailing "/*" catch-all, or "" if the route had no wildcard.
func WriteBadRequest ¶
func WriteBadRequest(w http.ResponseWriter, err error)
WriteBadRequest writes err with HTTP 400.
func WriteError ¶
func WriteError(w http.ResponseWriter, status int, err error)
WriteError writes err as a JSON ErrorResponse with the given status code. Callers map domain errors to status codes themselves.
Types ¶
type Authorizer ¶
type Authorizer interface {
Authorize(ctx context.Context, action Action, resourceID string) error
}
Authorizer is called before privileged operations. Return nil to allow, ErrUnauthorized to deny, or any other error to signal an infrastructure failure.
resourceID identifies the target resource; it may be empty for collection-level operations. Read identity from ctx via OrgIDFromContext / UserIDFromContext.
type ClaimsExtractor ¶
ClaimsExtractor parses a raw Bearer token and returns the claims. Return a non-nil error to reject the request with HTTP 401.
type Config ¶
Config configures a Server's listen address. Anything beyond the address (timeouts, TLS, connection hooks) is set via Option or by mutating the underlying server returned by HTTP.
type ErrorResponse ¶
type ErrorResponse struct {
Error string `json:"error"`
}
ErrorResponse is the canonical JSON error body.
type HandleRouter ¶
HandleRouter is the minimal interface satisfied by any HTTP framework that can register a method+pattern+handler triple. *Router satisfies it.
type Logger ¶
type Logger interface {
Trace(msg string, args ...any)
Debug(msg string, args ...any)
Info(msg string, args ...any)
Warn(msg string, args ...any)
Error(msg string, args ...any)
}
Logger is the minimal leveled logging surface the server writes to. It is satisfied structurally by github.com/toaweme/log's Slog, so callers can inject that directly, or a null logger to discard output. It is defined here rather than imported from the client module so the server module never depends on its parent; a single concrete logger satisfies both.
type Option ¶
Option mutates the underlying *http.Server during construction. Options run after the defaults (Addr, Handler, ReadHeaderTimeout) are applied, so they can override anything.
func WithIdleTimeout ¶
WithIdleTimeout sets how long to keep a keep-alive connection idle.
func WithReadHeaderTimeout ¶
WithReadHeaderTimeout sets how long the server waits for request headers. Pass 0 to disable it (not recommended - exposes the server to Slowloris).
func WithReadTimeout ¶
WithReadTimeout sets the maximum duration for reading an entire request.
func WithWriteTimeout ¶
WithWriteTimeout sets the maximum duration before timing out response writes.
type Route ¶
Route is a single HTTP route definition. Pattern uses net/http 1.22+ placeholder syntax: {name}.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router is the chi-backed request router exposed by this package.
func (*Router) Delete ¶
func (r *Router) Delete(p string, h http.HandlerFunc)
Delete registers h for DELETE requests to pattern p.
func (*Router) Get ¶
func (r *Router) Get(p string, h http.HandlerFunc)
Get registers h for GET requests to pattern p.
func (*Router) Group ¶
Group creates a sub-router rooted at prefix. Middleware added inside fn applies only to routes registered on the sub-router.
func (*Router) Handle ¶
Handle registers handler for method+pattern. Pattern uses chi's syntax, which mirrors stdlib's {name} placeholders for single segments and adds a trailing /* for catch-all.
func (*Router) Patch ¶
func (r *Router) Patch(p string, h http.HandlerFunc)
Patch registers h for PATCH requests to pattern p.
func (*Router) Post ¶
func (r *Router) Post(p string, h http.HandlerFunc)
Post registers h for POST requests to pattern p.
func (*Router) Put ¶
func (r *Router) Put(p string, h http.HandlerFunc)
Put registers h for PUT requests to pattern p.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server wraps net/http.Server around a *Router. Implements the {Name, Start, Stop} contract expected by go-shared/service.Service.
func NewServer ¶
NewServer wires a Server around the router. A github.com/toaweme/log logger can be injected directly, or a null logger to discard output. Pass Options to tune the underlying *http.Server, or reach for HTTP to set fields no Option covers.
func (*Server) HTTP ¶
HTTP returns the underlying *http.Server for callers that need to set fields no Option covers (TLS config, connection state hooks, error log, ...). Mutate it before calling Start; changes after the server is serving have no effect.
type SlogConfig ¶
type SlogConfig struct {
// LogRequestBody captures and logs the request body.
LogRequestBody bool
// LogResponseBody captures and logs the response body.
LogResponseBody bool
// LogRequestHeaders logs incoming request headers.
LogRequestHeaders bool
// LogResponseHeaders logs outgoing response headers (captured at end of request).
LogResponseHeaders bool
// MaxBodyBytes caps how much of each body is captured. 0 means no cap.
MaxBodyBytes int
}
SlogConfig controls what the SlogMiddleware emits on each request. LogRequestBody and LogResponseBody are off by default — they're useful for local debugging but should stay off in prod (PII, large payloads, perf).