Documentation
¶
Overview ¶
Package sein provides a high-performance, contract-first HTTP server framework for Go.
Overview ¶
Sein is designed around pure mathematical functions, zero-allocation radix routing, and single-contract DTO ingestion. Handlers declare all expected inputs (path, query, headers, cookies, auth tokens, client telemetry, multipart files, L1 context sessions, and JSON bodies) in a single unified struct.
Unified DTO Quick Reference ¶
A canonical example illustrating all available DTO binding sources, sanitizers, and validation rules:
type UpdateProfileDTO struct {
// 1. Data Sources (Where values originate from)
UserID uuid.UUID `path:"user_id" validate:"uuid"` // URL Path variable: /users/:user_id
Search string `query:"q,default=all" sanitize:"trim,lower"` // Query string: ?q=...
Page int `query:"page,default=1" validate:"positive"` // Query with integer parsing
Limit int `query:"limit,default=20" validate:"multiple_of=5,le=100"` // Step increment
Tags []string `query:"tags,sep=|"` // Slice with custom delimiter
TraceID string `header:"X-Trace-ID" validate:"required"` // HTTP Header
SessionID string `cookie:"session_id" validate:"required"` // Cookie value
AuthToken string `auth:"bearer,required"` // Authorization: Bearer <token>
ClientIP net.IP `net:"ip"` // Client IP (net.IP or netip.Addr)
Scheme string `net:"scheme"` // http or https
Avatar *sein.File `file:"avatar,required"` // Multipart form file
Gallery []*sein.File `files:"gallery"` // Multipart file collection
Category string `form:"category" sanitize:"trim"` // Multipart / urlencoded form field
RawHMAC []byte `query:"hmac" validate:"hex"` // Hex-decoded binary slice
PayloadB64 []byte `json:"payload" validate:"base64"` // Base64-decoded binary slice
Password sein.Secret[string] `json:"password" validate:"min=8"` // Sensitive data masked in logs
UserSession *Session `ctx:""` // Typed L1 context session
Bio string `json:"bio" validate:"max=500" sanitize:"squish"` // JSON body with whitespace collapsed
}
Tag Directives Reference ¶
1. Sources (Declare where values originate):
- `path:"key"` or `param:"key"`: URL path parameter (e.g. /users/:id)
- `query:"key"`: URL query parameter
- `header:"key"`: HTTP request header
- `cookie:"key"`: HTTP cookie
- `auth:"bearer"`: Authorization Bearer token
- `net:"ip"` / `net:"proto"` / `net:"scheme"` / `net:"host"` / `net:"method"` / `net:"path"`: Telemetry
- `form:"key"`: Form field (multipart or urlencoded)
- `file:"key"`: Single multipart uploaded file (*sein.File)
- `files:"key"`: Multiple multipart uploaded files ([]*sein.File)
- `body:"raw"` / `body:"string"`: Raw request body ([]byte or string)
- `ctx:""` / `context:""`: L1 typed request context injection
- `json:"key"`: JSON body payload field (standard encoding/json compatible)
2. Modifiers & Parameter Options:
- `default=value`: Fallback value when parameter is missing or empty
- `format="layout"`: Custom timestamp layout for time.Time fields
- `sep="delimiter"`: Custom slice element separator (default is ",")
- `sign` / `signed`: Cryptographically signed cookie verification
3. String Sanitizers (`sanitize:"..."`):
- `trim`: Strips leading and trailing whitespace
- `lower`: Converts ASCII characters to lowercase
- `upper`: Converts ASCII characters to uppercase
- `single_space` / `squish`: Replaces consecutive whitespace runs with a single space
- `digits_only`: Strips all non-digit characters
4. Declarative Validation Rules (`validate:"..."`):
- `required`: Field must be present and non-empty
- `min=N` / `max=N`: Minimum / maximum string length or numeric value
- `len=N`: Exact string length
- `gt=N` / `ge=N` / `lt=N` / `le=N`: Strict numeric inequalities
- `positive` / `negative` / `non_negative`: Numeric sign predicates
- `multiple_of=N`: Enforces that numeric value is divisible by N
- `enum=a|b|c`: Value must match one of the pipe-separated allowed options
- `pattern=regex`: Precompiled regular expression match
- `email`: Validates standard email address format
- `uuid`: Validates RFC 9562 / RFC 4122 UUID format
- `url`: Validates absolute URL format
- `hex`: Decodes hex-encoded string into []byte
- `base64`: Decodes base64-encoded string into []byte
5. Custom Domain Validation:
If a DTO struct implements the Validatable interface, its Validate() error method is automatically invoked after all declarative validations pass:
func (d *UpdateProfileDTO) Validate() error {
if d.Search == "" && d.Bio == "" {
return errors.New("at least one of search or bio must be provided")
}
return nil
}
Example ¶
package main
import (
"context"
"fmt"
"net"
"net/http"
"net/http/httptest"
"strings"
"github.com/lemon4ksan/foundation/types/uuid"
"github.com/lemon4ksan/sein"
)
// UserRequestDTO demonstrates a complete contract binding path, query, header, and body.
type UserRequestDTO struct {
UserID uuid.UUID `path:"id,uuid"`
Query string `query:"q,default=active,trim,lower"`
Limit int `query:"limit,default=25,positive,multiple_of=5"`
TraceID string `header:"X-Trace-ID,required"`
ClientIP net.IP `net:"ip"`
Password sein.Secret[string] `json:"password" validate:"min=8"`
}
type ExampleUserResponse struct {
Limit int `json:"limit"`
Password string `json:"password"`
Query string `json:"query"`
TraceID string `json:"trace_id"`
UserID string `json:"user_id"`
}
func main() {
app := sein.New()
app.Post("/users/:id", func(ctx context.Context, req UserRequestDTO) (ExampleUserResponse, error) {
return ExampleUserResponse{
UserID: req.UserID.String(),
Query: req.Query,
Limit: req.Limit,
TraceID: req.TraceID,
Password: req.Password.String(), // Returns masked "******"
}, nil
})
httpReq := httptest.NewRequest(
http.MethodPost,
"/users/a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11?q=+ADMIN+&limit=50",
strings.NewReader(`{"password":"my-secret-password"}`),
)
httpReq.Header.Set("X-Trace-ID", "trace-98765")
httpReq.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
app.ServeHTTP(rec, httpReq)
fmt.Println(rec.Body.String())
}
Output: {"limit":50,"password":"******","query":"admin","trace_id":"trace-98765","user_id":"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"}
Index ¶
- Variables
- func AddTiming(ctx context.Context, name string, dur time.Duration, description ...string)
- func Defer(ctx context.Context, fn func())
- func Get[T any](r *Request) (T, bool)
- func Handle(r RouteBuilder, method, path string, fn RawHandler, mw ...Middleware)
- func IngestDTO[T any](req *Request, dest *T) error
- func MustGet[T any](r *Request) T
- func Set[T any](r *Request, val T)
- func SignCookieValue(value string, secret string) string
- func StartTimer(ctx context.Context, name string, description ...string) func()
- func ValidateRouteBinding[T any](routePath string)
- func ValidateRouteBindingType(typ reflect.Type, routePath string)
- func VerifyCookieValue(signedValue string, secret string) (string, bool)
- func WithValue[T any](ctx context.Context, val T) context.Context
- type AfterResponseHook
- type DefinedError
- func BadGateway(code string, message ...string) DefinedError
- func BadRequest(code string, message ...string) DefinedError
- func Conflict(code string, message ...string) DefinedError
- func DefineError(status int, code, message string) DefinedError
- func ExpectationFailed(code string, message ...string) DefinedError
- func FailedDependency(code string, message ...string) DefinedError
- func Forbidden(code string, message ...string) DefinedError
- func GatewayTimeout(code string, message ...string) DefinedError
- func Gone(code string, message ...string) DefinedError
- func HTTPVersionNotSupported(code string, message ...string) DefinedError
- func HeaderFieldsTooLarge(code string, message ...string) DefinedError
- func InsufficientStorage(code string, message ...string) DefinedError
- func Internal(code string, message ...string) DefinedError
- func InternalServerError(code string, message ...string) DefinedError
- func LengthRequired(code string, message ...string) DefinedError
- func Locked(code string, message ...string) DefinedError
- func LoopDetected(code string, message ...string) DefinedError
- func MethodNotAllowed(code string, message ...string) DefinedError
- func MisdirectedRequest(code string, message ...string) DefinedError
- func NetworkAuthRequired(code string, message ...string) DefinedError
- func NotAcceptable(code string, message ...string) DefinedError
- func NotExtended(code string, message ...string) DefinedError
- func NotFound(code string, message ...string) DefinedError
- func NotImplemented(code string, message ...string) DefinedError
- func PayloadTooLarge(code string, message ...string) DefinedError
- func PaymentRequired(code string, message ...string) DefinedError
- func PreconditionFailed(code string, message ...string) DefinedError
- func PreconditionRequired(code string, message ...string) DefinedError
- func ProxyAuthRequired(code string, message ...string) DefinedError
- func RangeNotSatisfiable(code string, message ...string) DefinedError
- func RequestTimeout(code string, message ...string) DefinedError
- func ServiceUnavailable(code string, message ...string) DefinedError
- func Teapot(code string, message ...string) DefinedError
- func TooEarly(code string, message ...string) DefinedError
- func TooManyRequests(code string, message ...string) DefinedError
- func URITooLong(code string, message ...string) DefinedError
- func Unauthorized(code string, message ...string) DefinedError
- func UnavailableForLegalReasons(code string, message ...string) DefinedError
- func Unprocessable(code string, message ...string) DefinedError
- func UnprocessableEntity(code string, message ...string) DefinedError
- func UnsupportedMediaType(code string, message ...string) DefinedError
- func UpgradeRequired(code string, message ...string) DefinedError
- func VariantAlsoNegotiates(code string, message ...string) DefinedError
- func (d DefinedError) Details() map[string]any
- func (d DefinedError) Error() string
- func (d DefinedError) ErrorCode() string
- func (d DefinedError) HTTPStatus() int
- func (d DefinedError) Message() string
- func (d DefinedError) Unwrap() error
- func (d DefinedError) WithCause(err error) DefinedError
- func (d DefinedError) WithDetail(key string, val any) DefinedError
- func (d DefinedError) WithMessage(msg string) DefinedError
- type DirectH1Responder
- type DomainError
- type ErrorMap
- type ErrorMapper
- type ErrorMapperFunc
- type Errors
- type File
- type Group
- func (g *Group) Delete(path string, handler any, mw ...Middleware)
- func (g *Group) DeleteAuth[Res, Auth any](path string, fn func(context.Context, Auth) (Res, error), mw ...Middleware)
- func (g *Group) DeleteWithAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), ...)
- func (g *Group) Derive(t reflect.Type, fn any) *Group
- func (g *Group) Get(path string, handler any, mw ...Middleware)
- func (g *Group) GetAuth[Res, Auth any](path string, fn func(context.Context, Auth) (Res, error), mw ...Middleware)
- func (g *Group) GetWithAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), ...)
- func (g *Group) Group(prefix string, mw ...Middleware) *Group
- func (g *Group) Guard(mw ...Middleware) *GuardScope
- func (g *Group) Head(path string, handler any, mw ...Middleware)
- func (g *Group) MapError(target error, domainErr DomainError) *Group
- func (g *Group) MapErrors(errorsMap Errors) *Group
- func (g *Group) Mount(prefix string, m Module, mw ...Middleware) *Group
- func (g *Group) Options(path string, handler any, mw ...Middleware)
- func (g *Group) Patch(path string, handler any, mw ...Middleware)
- func (g *Group) PatchAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), ...)
- func (g *Group) Post(path string, handler any, mw ...Middleware)
- func (g *Group) PostAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), ...)
- func (g *Group) Put(path string, handler any, mw ...Middleware)
- func (g *Group) PutAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), ...)
- func (g *Group) Use(mw ...Middleware)
- type GuardScope
- type HTTPError
- func AsHTTPError(err error) (HTTPError, bool)
- func ErrBadRequest(message string, cause ...error) HTTPError
- func ErrConflict(message string, cause ...error) HTTPError
- func ErrForbidden(message string, cause ...error) HTTPError
- func ErrGatewayTimeout(message string, cause ...error) HTTPError
- func ErrInternal(message string, cause ...error) HTTPError
- func ErrNotFound(message string, cause ...error) HTTPError
- func ErrRequestEntityTooLarge(message string, cause ...error) HTTPError
- func ErrTooEarly(message string, cause ...error) HTTPError
- func ErrTooManyRequests(message string, cause ...error) HTTPError
- func ErrUnauthorized(message string, cause ...error) HTTPError
- func ErrUnprocessable(message string, cause ...error) HTTPError
- func NewError(status int, message string, cause ...error) HTTPError
- func NewHTTPError(status int, code, message string) HTTPError
- type HeaderParamDef
- type Ingestable
- type Middleware
- type Module
- type ModuleFunc
- type Option
- func WithAddr(addr string) Option
- func WithAutoTLS(domains ...string) Option
- func WithAutoTLSCacheDir(dir string) Option
- func WithCookieSecret(secret string) Option
- func WithMethodNotAllowed(enabled bool) Option
- func WithPrefork(enabled bool) Option
- func WithSkipUnmatchedRoutes(enabled bool) Option
- func WithTrailingSlashRedirect(enabled bool) Option
- func WithTrustedPlatform(headerName string) Option
- func WithTrustedProxies(proxies []string) Option
- type ParamConstraint
- type ParamSlot
- type ParamValue
- func (p ParamValue) AsBool(fallback ...bool) bool
- func (p ParamValue) AsInt(fallback ...int) int
- func (p ParamValue) AsInt64(fallback ...int64) int64
- func (p ParamValue) AsUint64(fallback ...uint64) uint64
- func (p ParamValue) Bool() (bool, error)
- func (p ParamValue) Int() (int, error)
- func (p ParamValue) Int64() (int64, error)
- func (p ParamValue) IsEmpty() bool
- func (p ParamValue) String() string
- func (p ParamValue) Uint64() (uint64, error)
- type Params
- type PathParamDef
- type QueryParamDef
- type RawHandler
- type RedirectError
- func (e RedirectError) Error() string
- func (e RedirectError) ErrorCode() string
- func (e RedirectError) HTTPStatus() int
- func (e RedirectError) Location() string
- func (e RedirectError) ResponseBody() any
- func (e RedirectError) ResponseCookies() []*http.Cookie
- func (e RedirectError) ResponseHeaders() http.Header
- func (e RedirectError) StatusCode() int
- type Request
- func FromContext(ctx context.Context) (*Request, bool)
- func NewH1Request(h1Req *h1engine.Request, params ...*Params) *Request
- func NewH2Request(method, path, authority, remoteAddr string, rawHeaders http.Header, ...) *Request
- func NewH3Request(method, path, authority, remoteAddr string, rawHeaders http.Header, ...) *Request
- func NewRequest(r *http.Request, params ...*Params) *Request
- func (r *Request) AddTiming(name string, dur time.Duration, description ...string)
- func (r *Request) AllocBytes(size int) []byte
- func (r *Request) AllocString(s string) string
- func (r *Request) Arena() *borrow.Scope
- func (r *Request) BearerToken() (string, bool)
- func (r *Request) Bind(dest any) error
- func (r *Request) BindJSON(dest any) error
- func (r *Request) Body() []byte
- func (r *Request) ClientIP() string
- func (r *Request) ClientIPWithTrust(trustedProxies []netip.Prefix) string
- func (r *Request) Context() context.Context
- func (r *Request) Cookie(name string) (string, error)
- func (r *Request) CookieSecret() string
- func (r *Request) Cookies() []*http.Cookie
- func (r *Request) Defer(fn func())
- func (r *Request) DelHeader(key string)
- func (r *Request) Detach()
- func (r *Request) EarlyHints(headers http.Header) error
- func (r *Request) EarlyHintsLinks(links ...string) error
- func (r *Request) FormFile(key string) (*File, error)
- func (r *Request) FormFiles(key string) ([]*File, error)
- func (r *Request) FormValue(key string) string
- func (r *Request) Header(key string) string
- func (r *Request) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (r *Request) Host() string
- func (r *Request) IP() string
- func (r *Request) IPs() []string
- func (r *Request) IfModifiedSince(lastModified time.Time) bool
- func (r *Request) IfNoneMatch(etag string) bool
- func (r *Request) Method() string
- func (r *Request) Param(name string) ParamValue
- func (r *Request) ParamMap() map[string]string
- func (r *Request) Params() *Params
- func (r *Request) Path() string
- func (r *Request) Proto() string
- func (r *Request) Protocol() string
- func (r *Request) Query(key string) ParamValue
- func (r *Request) Raw() *http.Request
- func (r *Request) RawBody() []byte
- func (r *Request) Release()
- func (r *Request) RemoteAddr() string
- func (r *Request) RoutePattern() string
- func (r *Request) SaveUploadedFile(file *File, dstPath string) error
- func (r *Request) Scheme() string
- func (r *Request) Scope() *borrow.Scope
- func (r *Request) ServerTimingHeader() string
- func (r *Request) SetBody(body []byte)
- func (r *Request) SetContext(ctx context.Context)
- func (r *Request) SetCookieSecret(secret string)
- func (r *Request) SetHeader(key, val string)
- func (r *Request) SetMethod(method string)
- func (r *Request) SetPath(path string)
- func (r *Request) SetQuery(query string)
- func (r *Request) SetRoutePattern(pattern string)
- func (r *Request) StartTimer(name string, description ...string) func()
- func (r *Request) WithContext(ctx context.Context) *Request
- type ResolverFunc
- type Responder
- type Response
- func Accepted[T any](body T) Response[T]
- func Created[T any](body T) Response[T]
- func HTML(content string) Response[string]
- func NoContent() Response[any]
- func NotModified() Response[any]
- func OK[T any](body T) Response[T]
- func Redirect(targetURL string, status ...int) Response[any]
- func RedirectTo[T any](targetURL string, status ...int) Response[T]
- func StatusWith[T any](status int, body T, headers http.Header) Response[T]
- func (r Response[T]) ResponseBody() any
- func (r Response[T]) ResponseCookies() []*http.Cookie
- func (r Response[T]) ResponseHeaders() http.Header
- func (r Response[T]) StatusCode() int
- func (r Response[T]) WithCookie(c *http.Cookie) Response[T]
- func (r Response[T]) WithETag(etag string) Response[T]
- func (r Response[T]) WithHeader(key, value string) Response[T]
- func (r Response[T]) WithHeaders(headers http.Header) Response[T]
- func (r Response[T]) WithLastModified(t time.Time) Response[T]
- func (r Response[T]) WithStatus(code int) Response[T]
- func (r Response[T]) WriteResponse(w http.ResponseWriter) error
- func (r Response[T]) WriteToH1(res *h1engine.Response) error
- type ResponseHolder
- type RouteBuilder
- type RouteInfo
- type Router
- func (r *Router) Add(method, pattern string, handler RawHandler, handlerType ...reflect.Type)
- func (r *Router) AllowedMethods(path string) []string
- func (r *Router) FindTrailingSlash(method, path string) (string, bool)
- func (r *Router) HasPath(path string) bool
- func (r *Router) Match(method, path string, params *Params) (RawHandler, string, bool)
- func (r *Router) Routes() []RouteInfo
- type SSEResponse
- type SSESender
- type Secret
- type Server
- func (s *Server) AfterResponse(fn AfterResponseHook) *Server
- func (s *Server) Close() error
- func (s *Server) Delete(path string, handler any, mw ...Middleware)
- func (s *Server) DeleteAuth[Res, Auth any](path string, fn func(context.Context, Auth) (Res, error), mw ...Middleware)
- func (s *Server) DeleteWithAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), ...)
- func (s *Server) DispatchH1(h1Req *h1engine.Request, h1Res *h1engine.Response) error
- func (s *Server) DispatchH2(h2Req *h2engine.ServerRequest, h2Res *h2engine.ServerResponse) error
- func (s *Server) DispatchH3(h3Req *h3engine.ServerRequest, h3Res *h3engine.ServerResponse) error
- func (s *Server) Get(path string, handler any, mw ...Middleware)
- func (s *Server) GetAuth[Res, Auth any](path string, fn func(context.Context, Auth) (Res, error), mw ...Middleware)
- func (s *Server) GetWithAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), ...)
- func (s *Server) Group(prefix string, mw ...Middleware) *Group
- func (s *Server) Guard(mw ...Middleware) *GuardScope
- func (s *Server) Head(path string, handler any, mw ...Middleware)
- func (s *Server) Listen(addr string) error
- func (s *Server) ListenAndServe() error
- func (s *Server) ListenAndServeAutoTLS(addr string, domains ...string) error
- func (s *Server) ListenAndServeQUIC(addr, certFile, keyFile string) error
- func (s *Server) ListenAndServeTLS(certFile, keyFile string) error
- func (s *Server) ListenAndServeUniversal(addr, certFile, keyFile string) error
- func (s *Server) MapError(target error, domainErr DomainError) *Server
- func (s *Server) MapErrorFunc(fn ErrorMapper) *Server
- func (s *Server) MapErrors(errorsMap Errors) *Server
- func (s *Server) Mount(prefix string, m Module, mw ...Middleware) *Server
- func (s *Server) MountModule(m Module) *Server
- func (s *Server) MountRaw(method, pattern string, handler RawHandler, mw ...Middleware)
- func (s *Server) NoMethod(handler RawHandler)
- func (s *Server) NoRoute(handler RawHandler)
- func (s *Server) Options(path string, handler any, mw ...Middleware)
- func (s *Server) Patch(path string, handler any, mw ...Middleware)
- func (s *Server) PatchAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), ...)
- func (s *Server) Post(path string, handler any, mw ...Middleware)
- func (s *Server) PostAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), ...)
- func (s *Server) PrintRoutes() string
- func (s *Server) Put(path string, handler any, mw ...Middleware)
- func (s *Server) PutAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), ...)
- func (s *Server) Routes() []RouteInfo
- func (s *Server) Serve(ln net.Listener) error
- func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (s *Server) SetTrustedPlatform(platformHeader string)
- func (s *Server) SetTrustedProxies(proxies []string) error
- func (s *Server) Shutdown(ctx context.Context) error
- func (s *Server) Trace(fn TraceHook) *Server
- func (s *Server) Use(mw ...Middleware)
- func (s *Server) VersionMatrix(prefixFormatter func(version string) string, versions ...string) *VersionGroup
- func (s *Server) Versioned(versions ...string) *VersionGroup
- type ServerTimingEntry
- type StreamResponse
- type StreamWriterResponse
- type TraceHook
- type TraceInfo
- type Validatable
- type VersionGroup
- func (vg *VersionGroup) Between(minVersion, maxVersion string) *VersionGroup
- func (vg *VersionGroup) Delete(path string, handler any, mw ...Middleware)
- func (vg *VersionGroup) Do(fn func(g *VersionGroup)) *VersionGroup
- func (vg *VersionGroup) Except(versions ...string) *VersionGroup
- func (vg *VersionGroup) Get(path string, handler any, mw ...Middleware)
- func (vg *VersionGroup) Group(prefix string, mw ...Middleware) *VersionGroup
- func (vg *VersionGroup) Guard(mw ...Middleware) *VersionGuardScope
- func (vg *VersionGroup) Head(path string, handler any, mw ...Middleware)
- func (vg *VersionGroup) MapError(target error, domainErr DomainError) *VersionGroup
- func (vg *VersionGroup) MapErrors(errorsMap Errors) *VersionGroup
- func (vg *VersionGroup) Mount(prefix string, m Module, mw ...Middleware) *VersionGroup
- func (vg *VersionGroup) Only(versions ...string) *VersionGroup
- func (vg *VersionGroup) Options(path string, handler any, mw ...Middleware)
- func (vg *VersionGroup) Patch(path string, handler any, mw ...Middleware)
- func (vg *VersionGroup) Post(path string, handler any, mw ...Middleware)
- func (vg *VersionGroup) Put(path string, handler any, mw ...Middleware)
- func (vg *VersionGroup) Since(minVersion string) *VersionGroup
- func (vg *VersionGroup) Until(maxVersion string) *VersionGroup
- func (vg *VersionGroup) Use(mw ...Middleware) *VersionGroup
- type VersionGuardScope
- type VersionMatrix
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrMissingBearerToken = Unauthorized("MISSING_BEARER_TOKEN", "Authorization Bearer token is required") ErrInvalidBearerToken = Unauthorized("INVALID_BEARER_TOKEN", "Provided Bearer token is invalid or expired") ErrEmptyRequestBody = BadRequest("EMPTY_REQUEST_BODY", "Request body cannot be empty") ErrInvalidJSONPayload = BadRequest("INVALID_JSON_PAYLOAD", "Invalid JSON payload structure") ErrValidationFailed = BadRequest("VALIDATION_FAILED", "Request validation failed") ErrRouteNotFound = NotFound("ROUTE_NOT_FOUND", "Requested route was not found") ErrInternalPanic = Internal("INTERNAL_SERVER_PANIC", "An unexpected panic occurred") ErrMissingPathParam = BadRequest("MISSING_PATH_PARAM", "Required path parameter is missing") ErrInvalidPathParam = BadRequest("INVALID_PATH_PARAM", "Path parameter value is invalid") ErrMissingQueryParam = BadRequest("MISSING_QUERY_PARAM", "Required query parameter is missing") ErrInvalidQueryParam = BadRequest("INVALID_QUERY_PARAM", "Query parameter value is invalid") ErrMissingHeader = BadRequest("MISSING_HEADER", "Required header is missing") ErrInvalidHeader = BadRequest("INVALID_HEADER", "Header value is invalid") ErrMissingCookie = BadRequest("MISSING_COOKIE", "Required cookie is missing") ErrInvalidCookie = BadRequest("INVALID_COOKIE", "Cookie value is invalid") ErrMissingContext = Unauthorized("MISSING_CONTEXT", "Required context value is missing") )
Core framework sentinels (exported, customizable, checkable via errors.Is)
var DefaultTrustedProxies = []netip.Prefix{ netip.MustParsePrefix("127.0.0.0/8"), netip.MustParsePrefix("::1/128"), netip.MustParsePrefix("10.0.0.0/8"), netip.MustParsePrefix("172.16.0.0/12"), netip.MustParsePrefix("192.168.0.0/16"), netip.MustParsePrefix("169.254.0.0/16"), netip.MustParsePrefix("fe80::/10"), netip.MustParsePrefix("fc00::/7"), }
DefaultTrustedProxies defines common private and loopback network ranges for trusted proxy resolution.
Functions ¶
func AddTiming ¶
AddTiming records a named duration on the active request in ctx for the W3C Server-Timing header.
func Defer ¶
Defer registers a deferred callback on the active request in ctx to execute after the HTTP response is sent. If ctx does not contain an active HTTP request (e.g. cron or worker), fn is executed asynchronously in a goroutine.
func Get ¶
Get retrieves a typed value from the request's flat inline context storage (0 B/op).
Example ¶
if session, ok := sein.Get[*UserSession](req); ok {
log.Printf("Current user: %d", session.UserID)
}
func Handle ¶
func Handle(r RouteBuilder, method, path string, fn RawHandler, mw ...Middleware)
Handle registers a raw handler function on any RouteBuilder (Server or Group).
func IngestDTO ¶
IngestDTO extracts multi-source request data (Path, Query, Headers, Cookies, Auth, Net, Form, Files, Context, Body) into dest.
func MustGet ¶
MustGet retrieves a typed value from request storage, panicking if the value was not set.
Example ¶
session := sein.MustGet[*UserSession](req)
func Set ¶
Set stores a typed value in the request's flat inline context storage with 0 heap allocations.
Architectural Invariants: L1 CPU Cache Locality ¶
Stores up to 8 typed values in a contiguous inline array on the Request struct itself, allowing sub-nanosecond lookups directly in L1 CPU cache without map hashing overhead.
Example ¶
sein.Set(req, &UserSession{UserID: 42, Role: "admin"})
func SignCookieValue ¶
SignCookieValue generates a signed cookie value in "value.signature" format using HMAC-SHA256.
func StartTimer ¶
StartTimer starts a named W3C Server-Timing stopwatch on the active request in ctx, returning a stop callback.
func ValidateRouteBinding ¶
ValidateRouteBinding checks at server startup that all URL path parameters declared in path have corresponding bindings in the DTO type T.
func ValidateRouteBindingType ¶
ValidateRouteBindingType checks at server startup that all URL path parameters declared in path have corresponding bindings in typ.
func VerifyCookieValue ¶
VerifyCookieValue verifies a "value.signature" string against secret using HMAC-SHA256 with constant-time equality.
Types ¶
type AfterResponseHook ¶
AfterResponseHook is a lifecycle callback invoked asynchronously after an HTTP response has been flushed to the client.
type DefinedError ¶
type DefinedError struct {
// contains filtered or unexported fields
}
DefinedError is an immutable, zero-allocation domain error sentinel.
func BadGateway ¶
func BadGateway(code string, message ...string) DefinedError
BadGateway creates a 502 Bad Gateway domain error sentinel.
func BadRequest ¶
func BadRequest(code string, message ...string) DefinedError
BadRequest creates a 400 Bad Request domain error sentinel.
func Conflict ¶
func Conflict(code string, message ...string) DefinedError
Conflict creates a 409 Conflict domain error sentinel.
func DefineError ¶
func DefineError(status int, code, message string) DefinedError
DefineError creates a reusable, machine-readable domain error sentinel with a custom status code.
func ExpectationFailed ¶
func ExpectationFailed(code string, message ...string) DefinedError
ExpectationFailed creates a 417 Expectation Failed domain error sentinel.
func FailedDependency ¶
func FailedDependency(code string, message ...string) DefinedError
FailedDependency creates a 424 Failed Dependency domain error sentinel.
func Forbidden ¶
func Forbidden(code string, message ...string) DefinedError
Forbidden creates a 403 Forbidden domain error sentinel.
func GatewayTimeout ¶
func GatewayTimeout(code string, message ...string) DefinedError
GatewayTimeout creates a 504 Gateway Timeout domain error sentinel.
func Gone ¶
func Gone(code string, message ...string) DefinedError
Gone creates a 410 Gone domain error sentinel.
func HTTPVersionNotSupported ¶
func HTTPVersionNotSupported(code string, message ...string) DefinedError
HTTPVersionNotSupported creates a 505 HTTP Version Not Supported domain error sentinel.
func HeaderFieldsTooLarge ¶
func HeaderFieldsTooLarge(code string, message ...string) DefinedError
HeaderFieldsTooLarge creates a 431 Request Header Fields Too Large domain error sentinel.
func InsufficientStorage ¶
func InsufficientStorage(code string, message ...string) DefinedError
InsufficientStorage creates a 507 Insufficient Storage domain error sentinel.
func Internal ¶
func Internal(code string, message ...string) DefinedError
Internal creates a 500 Internal Server Error domain error sentinel.
func InternalServerError ¶
func InternalServerError(code string, message ...string) DefinedError
InternalServerError is an alias for Internal (500).
func LengthRequired ¶
func LengthRequired(code string, message ...string) DefinedError
LengthRequired creates a 411 Length Required domain error sentinel.
func Locked ¶
func Locked(code string, message ...string) DefinedError
Locked creates a 423 Locked domain error sentinel.
func LoopDetected ¶
func LoopDetected(code string, message ...string) DefinedError
LoopDetected creates a 508 Loop Detected domain error sentinel.
func MethodNotAllowed ¶
func MethodNotAllowed(code string, message ...string) DefinedError
MethodNotAllowed creates a 405 Method Not Allowed domain error sentinel.
func MisdirectedRequest ¶
func MisdirectedRequest(code string, message ...string) DefinedError
MisdirectedRequest creates a 421 Misdirected Request domain error sentinel.
func NetworkAuthRequired ¶
func NetworkAuthRequired(code string, message ...string) DefinedError
NetworkAuthRequired creates a 511 Network Authentication Required domain error sentinel.
func NotAcceptable ¶
func NotAcceptable(code string, message ...string) DefinedError
NotAcceptable creates a 406 Not Acceptable domain error sentinel.
func NotExtended ¶
func NotExtended(code string, message ...string) DefinedError
NotExtended creates a 510 Not Extended domain error sentinel.
func NotFound ¶
func NotFound(code string, message ...string) DefinedError
NotFound creates a 404 Not Found domain error sentinel.
func NotImplemented ¶
func NotImplemented(code string, message ...string) DefinedError
NotImplemented creates a 501 Not Implemented domain error sentinel.
func PayloadTooLarge ¶
func PayloadTooLarge(code string, message ...string) DefinedError
PayloadTooLarge creates a 413 Payload Too Large domain error sentinel.
func PaymentRequired ¶
func PaymentRequired(code string, message ...string) DefinedError
PaymentRequired creates a 402 Payment Required domain error sentinel.
func PreconditionFailed ¶
func PreconditionFailed(code string, message ...string) DefinedError
PreconditionFailed creates a 412 Precondition Failed domain error sentinel.
func PreconditionRequired ¶
func PreconditionRequired(code string, message ...string) DefinedError
PreconditionRequired creates a 428 Precondition Required domain error sentinel.
func ProxyAuthRequired ¶
func ProxyAuthRequired(code string, message ...string) DefinedError
ProxyAuthRequired creates a 407 Proxy Authentication Required domain error sentinel.
func RangeNotSatisfiable ¶
func RangeNotSatisfiable(code string, message ...string) DefinedError
RangeNotSatisfiable creates a 416 Range Not Satisfiable domain error sentinel.
func RequestTimeout ¶
func RequestTimeout(code string, message ...string) DefinedError
RequestTimeout creates a 408 Request Timeout domain error sentinel.
func ServiceUnavailable ¶
func ServiceUnavailable(code string, message ...string) DefinedError
ServiceUnavailable creates a 503 Service Unavailable domain error sentinel.
func Teapot ¶
func Teapot(code string, message ...string) DefinedError
Teapot creates a 418 I'm a teapot domain error sentinel.
func TooEarly ¶
func TooEarly(code string, message ...string) DefinedError
TooEarly creates a 425 Too Early domain error sentinel.
func TooManyRequests ¶
func TooManyRequests(code string, message ...string) DefinedError
TooManyRequests creates a 429 Too Many Requests domain error sentinel.
func URITooLong ¶
func URITooLong(code string, message ...string) DefinedError
URITooLong creates a 414 URI Too Long domain error sentinel.
func Unauthorized ¶
func Unauthorized(code string, message ...string) DefinedError
Unauthorized creates a 401 Unauthorized domain error sentinel.
func UnavailableForLegalReasons ¶
func UnavailableForLegalReasons(code string, message ...string) DefinedError
UnavailableForLegalReasons creates a 451 Unavailable For Legal Reasons domain error sentinel.
func Unprocessable ¶
func Unprocessable(code string, message ...string) DefinedError
Unprocessable creates a 422 Unprocessable Entity domain error sentinel.
func UnprocessableEntity ¶
func UnprocessableEntity(code string, message ...string) DefinedError
UnprocessableEntity is an alias for Unprocessable (422).
func UnsupportedMediaType ¶
func UnsupportedMediaType(code string, message ...string) DefinedError
UnsupportedMediaType creates a 415 Unsupported Media Type domain error sentinel.
func UpgradeRequired ¶
func UpgradeRequired(code string, message ...string) DefinedError
UpgradeRequired creates a 426 Upgrade Required domain error sentinel.
func VariantAlsoNegotiates ¶
func VariantAlsoNegotiates(code string, message ...string) DefinedError
VariantAlsoNegotiates creates a 506 Variant Also Negotiates domain error sentinel.
func (DefinedError) Details ¶
func (d DefinedError) Details() map[string]any
func (DefinedError) Error ¶
func (d DefinedError) Error() string
func (DefinedError) ErrorCode ¶
func (d DefinedError) ErrorCode() string
func (DefinedError) HTTPStatus ¶
func (d DefinedError) HTTPStatus() int
func (DefinedError) Message ¶
func (d DefinedError) Message() string
func (DefinedError) Unwrap ¶
func (d DefinedError) Unwrap() error
func (DefinedError) WithCause ¶
func (d DefinedError) WithCause(err error) DefinedError
WithCause wraps an underlying root-cause error.
func (DefinedError) WithDetail ¶
func (d DefinedError) WithDetail(key string, val any) DefinedError
WithDetail adds a key-value detail field to the error payload.
func (DefinedError) WithMessage ¶
func (d DefinedError) WithMessage(msg string) DefinedError
WithMessage overrides the human-readable error message.
type DirectH1Responder ¶
DirectH1Responder is an interface for direct serialization to the native H1 response.
type DomainError ¶
DomainError is the standard interface for typed business domain errors. Any error implementing this interface automatically dictates its HTTP status code and machine-readable error code.
type ErrorMap ¶
type ErrorMap struct {
From error
To DomainError
}
ErrorMap represents a domain error translation pair from an underlying sentinel error to a DomainError.
type ErrorMapper ¶
type ErrorMapper func(err error) (DomainError, bool)
ErrorMapper translates arbitrary errors into typed DomainErrors.
type ErrorMapperFunc ¶
type ErrorMapperFunc func(error) (DomainError, bool)
ErrorMapperFunc translates internal sentinel errors into typed DomainErrors.
type Errors ¶
type Errors map[error]DomainError
Errors represents a dictionary table of error mappings (Target -> DomainError).
type File ¶
type File struct {
Filename string
Size int64
ContentType string
Header textproto.MIMEHeader
// contains filtered or unexported fields
}
File represents an uploaded multipart form file with zero-allocation streaming and direct disk-save helpers.
func NewFile ¶
func NewFile(fh *multipart.FileHeader) *File
NewFile constructs a File from a multipart.FileHeader.
func (*File) Open ¶
func (f *File) Open() (io.ReadCloser, error)
Open opens the underlying uploaded file stream for reading.
func (*File) SaveTo ¶
SaveTo streams the uploaded file directly to the specified destination filesystem path, automatically creating parent directories with restricted 0750 permissions if they do not exist.
Usage:
file, err := req.FormFile("avatar")
if err == nil {
err = file.SaveTo("/var/uploads/avatars/" + file.Filename)
}
Performance: Streams bytes directly from the multipart temporary storage via io.Copy without loading the entire payload into heap memory (0 B buffer allocations).
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group represents a scoped router group with a path prefix, scoped middlewares, and domain error mappers.
func GroupDerive ¶
func GroupDerive[T any](g *Group, fn ResolverFunc[T]) *Group
GroupDerive registers a typed resolver on a group.
func GroupProvide ¶
func GroupProvide[T any](g *Group, fn ResolverFunc[T]) *Group
GroupProvide is an alias for GroupDerive.
func NewGroup ¶
func NewGroup(parent RouteBuilder, prefix string, mw ...Middleware) *Group
NewGroup creates a new route Group attached to a parent RouteBuilder.
func (*Group) Delete ¶
func (g *Group) Delete(path string, handler any, mw ...Middleware)
Delete registers a route handler on DELETE on this group: accepts any valid handler signature.
func (*Group) DeleteAuth ¶
func (g *Group) DeleteAuth[Res, Auth any](path string, fn func(context.Context, Auth) (Res, error), mw ...Middleware)
DeleteAuth registers a DELETE handler on a group: (ctx, Auth) -> (Res, error)
func (*Group) DeleteWithAuth ¶
func (g *Group) DeleteWithAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), mw ...Middleware)
DeleteWithAuth registers a DELETE handler on a group with request DTO and Auth: (ctx, Req, Auth) -> (Res, error)
func (*Group) Get ¶
func (g *Group) Get(path string, handler any, mw ...Middleware)
Get registers a route handler on GET on this group: accepts any valid handler signature.
func (*Group) GetAuth ¶
func (g *Group) GetAuth[Res, Auth any](path string, fn func(context.Context, Auth) (Res, error), mw ...Middleware)
GetAuth registers a GET handler on a group: (ctx, Auth) -> (Res, error)
func (*Group) GetWithAuth ¶
func (g *Group) GetWithAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), mw ...Middleware)
GetWithAuth registers a GET handler on a group with request DTO and Auth: (ctx, Req, Auth) -> (Res, error)
func (*Group) Group ¶
func (g *Group) Group(prefix string, mw ...Middleware) *Group
Group creates a nested sub-group under this group's prefix.
func (*Group) Guard ¶
func (g *Group) Guard(mw ...Middleware) *GuardScope
Guard creates a protected GuardScope within this group with the given middlewares applied.
func (*Group) Head ¶
func (g *Group) Head(path string, handler any, mw ...Middleware)
Head registers a route handler on HEAD on this group.
func (*Group) MapError ¶
func (g *Group) MapError(target error, domainErr DomainError) *Group
MapError registers a mapping from an internal sentinel error to a Sein domain error.
func (*Group) MapErrors ¶
MapErrors registers multiple error mappings on the group using an Errors table.
func (*Group) Mount ¶
func (g *Group) Mount(prefix string, m Module, mw ...Middleware) *Group
Mount attaches a domain Module under this group with optional additional middlewares.
func (*Group) Options ¶
func (g *Group) Options(path string, handler any, mw ...Middleware)
Options registers a route handler on OPTIONS on this group.
func (*Group) Patch ¶
func (g *Group) Patch(path string, handler any, mw ...Middleware)
Patch registers a route handler on PATCH on this group: accepts any valid handler signature.
func (*Group) PatchAuth ¶
func (g *Group) PatchAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), mw ...Middleware)
PatchAuth registers a PATCH handler on a group: (ctx, Req, Auth) -> (Res, error)
func (*Group) Post ¶
func (g *Group) Post(path string, handler any, mw ...Middleware)
Post registers a route handler on POST on this group: accepts any valid handler signature.
func (*Group) PostAuth ¶
func (g *Group) PostAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), mw ...Middleware)
PostAuth registers a POST handler on a group: (ctx, Req, Auth) -> (Res, error)
func (*Group) Put ¶
func (g *Group) Put(path string, handler any, mw ...Middleware)
Put registers a route handler on PUT on this group: accepts any valid handler signature.
type GuardScope ¶
type GuardScope struct {
*Group
}
GuardScope represents a protected route scope that can conditionally mount routes via Do().
func (*GuardScope) Do ¶
func (gs *GuardScope) Do(fn func(g *Group)) *GuardScope
Do executes the callback within the protected GuardScope.
func (*GuardScope) MapError ¶
func (gs *GuardScope) MapError(target error, domainErr DomainError) *GuardScope
MapError registers a domain error mapping rule on the guard scope.
func (*GuardScope) MapErrors ¶
func (gs *GuardScope) MapErrors(errorsMap Errors) *GuardScope
MapErrors registers multiple scoped error mappings from an Errors table on the guard scope.
type HTTPError ¶
type HTTPError struct {
Status int `json:"status"`
Code string `json:"code,omitempty"`
Message string `json:"message"`
Details map[string]any `json:"details,omitempty"`
Cause error `json:"-"`
}
HTTPError is a generic semantic error structure for ad-hoc runtime errors.
func AsHTTPError ¶
AsHTTPError checks if an error wraps or is an HTTPError.
func ErrBadRequest ¶
ErrBadRequest creates a 400 Bad Request ad-hoc error.
func ErrConflict ¶
ErrConflict creates a 409 Conflict ad-hoc error.
func ErrForbidden ¶
ErrForbidden creates a 403 Forbidden ad-hoc error.
func ErrGatewayTimeout ¶
ErrGatewayTimeout creates a 504 Gateway Timeout ad-hoc error.
func ErrInternal ¶
ErrInternal creates a 500 Internal Server Error ad-hoc error.
func ErrNotFound ¶
ErrNotFound creates a 404 Not Found ad-hoc error.
func ErrRequestEntityTooLarge ¶
ErrRequestEntityTooLarge creates a 413 Request Entity Too Large ad-hoc error.
func ErrTooEarly ¶
ErrTooEarly creates a 425 Too Early ad-hoc error (RFC 8470).
func ErrTooManyRequests ¶
ErrTooManyRequests creates a 429 Too Many Requests ad-hoc error.
func ErrUnauthorized ¶
ErrUnauthorized creates a 401 Unauthorized ad-hoc error.
func ErrUnprocessable ¶
ErrUnprocessable creates a 422 Unprocessable Entity ad-hoc error.
func NewHTTPError ¶
NewHTTPError creates a structured HTTPError with status, code, and message.
func (HTTPError) HTTPStatus ¶
func (HTTPError) StatusCode ¶
type HeaderParamDef ¶
type HeaderParamDef[T ParamConstraint] struct { // contains filtered or unexported fields }
HeaderParamDef is a typed header descriptor.
func HeaderParam ¶
func HeaderParam[T ParamConstraint](name string) HeaderParamDef[T]
HeaderParam defines a typed header descriptor (e.g. sein.HeaderParam[string]("X-Token")).
func (HeaderParamDef[T]) Get ¶
func (h HeaderParamDef[T]) Get(req *Request) (T, error)
Get extracts and parses the header value from the request.
func (HeaderParamDef[T]) GetOr ¶
func (h HeaderParamDef[T]) GetOr(req *Request, fallback T) T
GetOr extracts the header or returns fallback if empty.
func (HeaderParamDef[T]) Name ¶
func (h HeaderParamDef[T]) Name() string
Name returns the header key name.
type Ingestable ¶
type Ingestable = binder.Ingestable
Ingestable is implemented by compiled DTOs (e.g. generated by vortex gen) for zero-reflection, multi-source ingestion.
type Middleware ¶
type Middleware func(next RawHandler) RawHandler
Middleware wraps a RawHandler in an onion chain.
func BearerAuth ¶
BearerAuth returns a middleware that extracts the Bearer token, validates it using validator, and injects the returned session of type T into the request's L1-cache inline storage (0 B/op). If the token is missing or invalid, it immediately halts the pipeline with a 401 Unauthorized error.
func DeriveMiddleware ¶
func DeriveMiddleware[T any](fn ResolverFunc[T]) Middleware
DeriveMiddleware creates a middleware that resolves dependency T and injects it into the request context and fast slots.
func ProvideMiddleware ¶
func ProvideMiddleware[T any](fn ResolverFunc[T]) Middleware
ProvideMiddleware is an alias for DeriveMiddleware.
func Recovery ¶
func Recovery() Middleware
Recovery returns a middleware that catches panics and turns them into 500 Internal Server Errors.
type Module ¶
type Module interface {
Mount(g *Group)
}
Module represents a self-contained domain component that mounts its endpoints onto a Group.
type ModuleFunc ¶
type ModuleFunc func(g *Group)
ModuleFunc is a functional adapter that satisfies the Module interface.
func (ModuleFunc) Mount ¶
func (f ModuleFunc) Mount(g *Group)
Mount implements Module for ModuleFunc.
type Option ¶
type Option func(s *Server)
Option configures a sein Server instance.
func WithAddr ¶
WithAddr configures the default listening network address (e.g. ":8080" or "0.0.0.0:443").
func WithAutoTLS ¶
WithAutoTLS configures zero-config automatic TLS certificate provisioning via ACME (Let's Encrypt / ZeroSSL).
func WithAutoTLSCacheDir ¶
WithAutoTLSCacheDir configures the directory used to persist ACME certificates on disk.
func WithCookieSecret ¶
WithCookieSecret configures a default secret key for HMAC signed cookie verification.
func WithMethodNotAllowed ¶
WithMethodNotAllowed configures whether 405 Method Not Allowed is automatically returned when a path exists for other HTTP verbs (RFC 9110 §15.5.6).
func WithPrefork ¶
WithPrefork enables high-load multi-process socket preforking on UNIX systems (`SO_REUSEPORT`).
func WithSkipUnmatchedRoutes ¶
WithSkipUnmatchedRoutes configures whether global middlewares are bypassed for unmatched routes (404 / 405).
func WithTrailingSlashRedirect ¶
WithTrailingSlashRedirect configures whether requests with mismatched trailing slashes are automatically redirected (RFC 9110 §15.4.2).
func WithTrustedPlatform ¶
WithTrustedPlatform sets a trusted platform header (e.g. "CF-Connecting-IP") for ClientIP extraction.
func WithTrustedProxies ¶
WithTrustedProxies configures trusted reverse proxy CIDRs/IPs for anti-spoofing Request.ClientIP resolution.
type ParamConstraint ¶
type ParamConstraint interface {
~string | ~uint64 | ~uint32 | ~uint16 | ~uint8 | ~uint |
~int64 | ~int32 | ~int16 | ~int8 | ~int | ~bool | ~float64 | ~float32
}
ParamConstraint defines supported primitive and scalar types for URL and Header parameters.
type ParamValue ¶
type ParamValue string
ParamValue represents a raw path parameter or query string value.
func (ParamValue) AsBool ¶
func (p ParamValue) AsBool(fallback ...bool) bool
AsBool returns the parsed bool or the fallback default if parsing fails.
func (ParamValue) AsInt ¶
func (p ParamValue) AsInt(fallback ...int) int
AsInt returns the parsed integer or the fallback default if parsing fails.
func (ParamValue) AsInt64 ¶
func (p ParamValue) AsInt64(fallback ...int64) int64
AsInt64 returns the parsed int64 or the fallback default if parsing fails.
func (ParamValue) AsUint64 ¶
func (p ParamValue) AsUint64(fallback ...uint64) uint64
AsUint64 returns the parsed uint64 or the fallback default if parsing fails.
func (ParamValue) Bool ¶
func (p ParamValue) Bool() (bool, error)
Bool parses the parameter into a boolean.
func (ParamValue) Int ¶
func (p ParamValue) Int() (int, error)
Int parses the parameter into an integer.
func (ParamValue) Int64 ¶
func (p ParamValue) Int64() (int64, error)
Int64 parses the parameter into an int64.
func (ParamValue) IsEmpty ¶
func (p ParamValue) IsEmpty() bool
IsEmpty reports whether the parameter is empty.
func (ParamValue) Uint64 ¶
func (p ParamValue) Uint64() (uint64, error)
Uint64 parses the parameter into a uint64.
type Params ¶
type Params struct {
// contains filtered or unexported fields
}
Params holds parsed URL path parameters with zero heap allocations for up to 8 parameters.
type PathParamDef ¶
type PathParamDef[T ParamConstraint] struct { // contains filtered or unexported fields }
PathParamDef is a typed path parameter descriptor.
func PathParam ¶
func PathParam[T ParamConstraint](name string) PathParamDef[T]
PathParam defines a typed path parameter descriptor (e.g. sein.PathParam[types.Snowflake]("id")).
func (PathParamDef[T]) Get ¶
func (p PathParamDef[T]) Get(req *Request) (T, error)
Get extracts and parses the path parameter from the request into type T.
func (PathParamDef[T]) GetOr ¶
func (p PathParamDef[T]) GetOr(req *Request, fallback T) T
GetOr extracts the path parameter or returns fallback if not valid.
func (PathParamDef[T]) MustGet ¶
func (p PathParamDef[T]) MustGet(req *Request) T
MustGet extracts the path parameter or panics if invalid/missing.
func (PathParamDef[T]) Name ¶
func (p PathParamDef[T]) Name() string
Name returns the parameter key name.
type QueryParamDef ¶
type QueryParamDef[T ParamConstraint] struct { // contains filtered or unexported fields }
QueryParamDef is a typed query parameter descriptor.
func QueryParam ¶
func QueryParam[T ParamConstraint](name string) QueryParamDef[T]
QueryParam defines a typed query parameter descriptor (e.g. sein.QueryParam[int]("page")).
func (QueryParamDef[T]) Get ¶
func (q QueryParamDef[T]) Get(req *Request) (T, error)
Get extracts and parses the query parameter from the request.
func (QueryParamDef[T]) GetOr ¶
func (q QueryParamDef[T]) GetOr(req *Request, fallback T) T
GetOr extracts the query parameter or returns fallback if not provided.
func (QueryParamDef[T]) Name ¶
func (q QueryParamDef[T]) Name() string
Name returns the query parameter key name.
type RawHandler ¶
RawHandler is the internal uniform handler signature returning any payload or error.
type RedirectError ¶
RedirectError represents an HTTP redirection returned as an error from a handler. This allows typed handlers (e.g. func(ctx) (*UserDTO, error)) to trigger an immediate redirect without altering their return type signature.
func ErrRedirect ¶
func ErrRedirect(targetURL string, status ...int) RedirectError
ErrRedirect creates a RedirectError pointing to targetURL.
Example ¶
app.Get("/avatar", func(ctx context.Context, req *GetAvatarReq) (*AvatarDTO, error) {
if req.External {
return nil, sein.ErrRedirect("https://gravatar.com/avatar/...", http.StatusTemporaryRedirect)
}
return &AvatarDTO{ID: req.ID}, nil
})
func (RedirectError) Error ¶
func (e RedirectError) Error() string
Error implements the error interface.
func (RedirectError) ErrorCode ¶
func (e RedirectError) ErrorCode() string
ErrorCode returns "REDIRECT".
func (RedirectError) HTTPStatus ¶
func (e RedirectError) HTTPStatus() int
HTTPStatus returns the HTTP redirection status code.
func (RedirectError) Location ¶
func (e RedirectError) Location() string
Location returns the target URL for redirection.
func (RedirectError) ResponseBody ¶
func (e RedirectError) ResponseBody() any
ResponseBody returns nil.
func (RedirectError) ResponseCookies ¶
func (e RedirectError) ResponseCookies() []*http.Cookie
ResponseCookies returns nil.
func (RedirectError) ResponseHeaders ¶
func (e RedirectError) ResponseHeaders() http.Header
ResponseHeaders returns the Location header map.
func (RedirectError) StatusCode ¶
func (e RedirectError) StatusCode() int
StatusCode returns the HTTP status code (implements ResponseHolder).
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
func FromContext ¶
FromContext retrieves the active *Request associated with the context, if present.
func NewH1Request ¶
NewH1Request creates a Request wrapping a native zero-net/http h1.Request.
func NewH2Request ¶
func NewH2Request( method, path, authority, remoteAddr string, rawHeaders http.Header, body []byte, params ...*Params, ) *Request
NewH2Request creates a Request wrapping a native H2 stream request.
func NewH3Request ¶
func NewH3Request( method, path, authority, remoteAddr string, rawHeaders http.Header, body []byte, params ...*Params, ) *Request
NewH3Request creates a Request wrapping a native H3 stream request.
func NewRequest ¶
NewRequest creates a Request wrapping a standard http.Request.
func (*Request) AddTiming ¶
AddTiming records an explicit execution duration for the W3C Server-Timing header (e.g. database query, redis, auth).
func (*Request) AllocBytes ¶
AllocBytes allocates a zero-copy byte slice of the requested size out of the per-request arena.
func (*Request) AllocString ¶
AllocString clones a string into the contiguous per-request arena buffer without heap allocation.
func (*Request) Arena ¶
Arena is an alias for Scope, providing a per-request bump allocator with zero GC overhead.
func (*Request) BearerToken ¶
BearerToken extracts the token from the "Authorization: Bearer <token>" header.
func (*Request) Bind ¶
Bind ingests the request path parameters, query parameters, headers, and payload into dest using the precompiled binder.
func (*Request) BindJSON ¶
BindJSON decodes the JSON request body into dest and executes automatic validation if dest implements Validatable.
func (*Request) Body ¶
Body reads and caches the full request body, automatically decompressing if Content-Encoding is present.
func (*Request) ClientIP ¶
ClientIP returns the real client IP address, checking platform headers (CF-Connecting-IP, Fly-Client-IP, True-Client-IP, X-Real-IP), and safely parsing X-Forwarded-For right-to-left using DefaultTrustedProxies to prevent IP spoofing attacks.
func (*Request) ClientIPWithTrust ¶
ClientIPWithTrust returns the real client IP address by traversing the X-Forwarded-For chain right-to-left, skipping any intermediate proxies matching the provided trusted IP prefixes.
func (*Request) Context ¶
Context returns the request-scoped context, automatically binding the active *Request.
func (*Request) CookieSecret ¶
CookieSecret returns the secret key used for signed cookie verification on this request.
func (*Request) Defer ¶
func (r *Request) Defer(fn func())
Defer registers a function to execute after the HTTP response has been completely written and flushed to the client.
Deferred callbacks execute in LIFO (last-in, first-out) order during request completion with panic recovery, allowing audit logs, telemetry metrics, and background jobs to run without delaying response time (TTFB).
func (*Request) Detach ¶
func (r *Request) Detach()
Detach prevents this Request from being returned to the memory pool upon completion (e.g. when abandoned to a background goroutine on timeout).
func (*Request) EarlyHints ¶
EarlyHints emits an intermediate HTTP 103 Early Hints response to the client with the specified headers (RFC 8297). Useful for preloading stylesheets, scripts, and fonts while background database queries execute.
func (*Request) EarlyHintsLinks ¶
EarlyHintsLinks emits 103 Early Hints preloading links (e.g. "</style.css>; rel=preload; as=style").
func (*Request) FormFiles ¶
FormFiles retrieves all uploaded files under key from multipart form data.
func (*Request) FormValue ¶
FormValue retrieves a value from POST/PUT form-encoded or multipart data.
func (*Request) Hijack ¶
Hijack takes over the raw underlying TCP connection from the server. Once hijacked, the server will not write any HTTP response and will not close the connection.
func (*Request) IfModifiedSince ¶
IfModifiedSince reports whether the resource has not been modified since the client's header timestamp (RFC 7232 §3.3).
func (*Request) IfNoneMatch ¶
IfNoneMatch reports whether the client's If-None-Match header matches etag (RFC 7232 §3.2).
func (*Request) Param ¶
func (r *Request) Param(name string) ParamValue
Param retrieves a URL path parameter by name (e.g. "id" for "/users/:id").
func (*Request) Proto ¶
Proto returns the HTTP protocol version (e.g. "HTTP/1.1", "HTTP/2.0", "HTTP/3.0").
func (*Request) Protocol ¶
Protocol returns the network protocol (e.g. "HTTP/1.1", "HTTP/2.0", "HTTP/3.0").
func (*Request) Query ¶
func (r *Request) Query(key string) ParamValue
Query retrieves a query parameter by key.
func (*Request) Raw ¶
Raw returns the underlying *http.Request for advanced compatibility if available.
func (*Request) Release ¶
func (r *Request) Release()
Release returns the Request and its internal borrow arena to the sharded per-P memory pool.
func (*Request) RemoteAddr ¶
RemoteAddr returns the raw remote network address (IP:port).
func (*Request) RoutePattern ¶
RoutePattern returns the registered route template pattern (e.g. "/users/:id"). If the route is an unmatched 404 or unregistered path, it defaults to Path().
func (*Request) SaveUploadedFile ¶
SaveUploadedFile streams an uploaded multipart file directly to dstPath on disk, automatically creating necessary parent directories with restricted 0750 permissions.
Usage:
s.Post("/upload", func(req *sein.Request, _ struct{}) (any, error) {
file, err := req.FormFile("document")
if err != nil {
return nil, err
}
return "uploaded", req.SaveUploadedFile(file, "/data/uploads/"+file.Filename)
})
func (*Request) Scheme ¶
Scheme returns the normalized request scheme ("https" or "http"). It strictly validates X-Forwarded-Proto and Forwarded headers to prevent Open Redirect and header injection vulnerabilities.
func (*Request) Scope ¶
Scope returns the request-scoped lexical arena, guaranteed to be recycled with 0 GC allocations on request finish.
func (*Request) ServerTimingHeader ¶
ServerTimingHeader formats all recorded timings into a compliant W3C Server-Timing header value. Format: name;dur=12.4;desc="Description", name2;dur=1.5
func (*Request) SetContext ¶
SetContext sets a new context on the request.
func (*Request) SetCookieSecret ¶
SetCookieSecret sets the secret key used for signed cookie verification on this request.
func (*Request) SetRoutePattern ¶
SetRoutePattern manually sets the route pattern for custom request dispatching.
func (*Request) StartTimer ¶
StartTimer starts a stopwatch for name and returns a stop function that records the elapsed time upon invocation.
Example ¶
stopDB := req.StartTimer("db", "PostgreSQL User Query")
user, err := db.GetUser(ctx, id)
stopDB()
type ResolverFunc ¶
ResolverFunc extracts a strongly-typed value T from an incoming HTTP request. If resolution fails (e.g. invalid JWT, missing session, expired token), the returned error is automatically written to the HTTP response and handler execution is aborted.
type Responder ¶
type Responder interface {
WriteResponse(w http.ResponseWriter) error
}
Responder is an interface that allows custom types to control their exact wire serialization for net/http.
type Response ¶
Response is a type-safe HTTP response container carrying status, headers, and body.
func Accepted ¶
Accepted creates a type-safe 202 Accepted Response for asynchronous background processing (RFC 9110 §15.3.3).
func Created ¶
Created creates a type-safe 201 Created Response wrapping body (RFC 9110 §15.3.2).
Example ¶
return sein.Created(User{ID: 42, Name: "Bob"}), nil
func NoContent ¶
NoContent creates a type-safe 204 No Content Response with an empty wire payload (RFC 9110 §15.3.5).
func NotModified ¶
NotModified creates a 304 Not Modified conditional cache Response (RFC 9110 §15.4.5).
func OK ¶
OK creates a type-safe 200 OK Response wrapping body.
Example ¶
return sein.OK(User{ID: 1, Name: "Alice"}), nil
func Redirect ¶
Redirect creates a 302 Found / 307 Temporary Redirect Response pointing to targetURL (RFC 9110 §15.4.3).
Example ¶
return sein.Redirect("/login"), nil
func RedirectTo ¶
RedirectTo creates a type-safe 302 Found / 307 Temporary Redirect Response pointing to targetURL. It allows handlers returning Response[T] to return a typed redirect response with zero allocations.
Example ¶
return sein.RedirectTo[*UserDTO]("/login"), nil
func StatusWith ¶
StatusWith creates a response with custom HTTP status code, body, and headers.
func (Response[T]) ResponseBody ¶
ResponseBody returns the generic body payload.
func (Response[T]) ResponseCookies ¶
ResponseCookies returns attached cookies.
func (Response[T]) ResponseHeaders ¶
ResponseHeaders returns the response headers map.
func (Response[T]) StatusCode ¶
StatusCode returns the HTTP status code.
func (Response[T]) WithCookie ¶
WithCookie attaches a set-cookie instruction to the response.
func (Response[T]) WithETag ¶
WithETag sets the ETag header with quotes automatically formatted if omitted.
func (Response[T]) WithHeader ¶
WithHeader adds a response header.
func (Response[T]) WithHeaders ¶
WithHeaders merges all key-value pairs from headers into the response.
func (Response[T]) WithLastModified ¶
WithLastModified sets the Last-Modified header formatted per RFC 7232.
func (Response[T]) WithStatus ¶
WithStatus changes the HTTP status code.
func (Response[T]) WriteResponse ¶
func (r Response[T]) WriteResponse(w http.ResponseWriter) error
WriteResponse serializes the response to the given http.ResponseWriter.
type ResponseHolder ¶
type ResponseHolder interface {
StatusCode() int
ResponseBody() any
ResponseHeaders() http.Header
ResponseCookies() []*http.Cookie
}
ResponseHolder allows middlewares to inspect response metadata and payload.
type RouteBuilder ¶
type RouteBuilder interface {
// contains filtered or unexported methods
}
RouteBuilder is the common abstraction shared between Server and Group.
type RouteInfo ¶
type RouteInfo struct {
// Method is the uppercase HTTP verb (e.g., "GET", "POST", "PUT", "DELETE").
Method string
// Path is the URL route pattern (e.g., "/users/:id", "/assets/*filepath").
Path string
// HandlerType is the reflected type of the handler function for automated OpenAPI introspection.
HandlerType reflect.Type
}
RouteInfo encapsulates metadata describing a registered route in the server routing tree. It is used for route inspection, introspection APIs, and automated OpenAPI schema generation.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router represents a high-throughput hybrid HTTP routing engine combining an O(1) hash-indexed static lookup table with a compact Radix Trie for parameterized routes.
func NewRouter ¶
func NewRouter() *Router
NewRouter instantiates an empty, initialized Router ready for route registrations.
func (*Router) Add ¶
func (r *Router) Add(method, pattern string, handler RawHandler, handlerType ...reflect.Type)
Add registers a new HTTP route pattern and its associated RawHandler.
func (*Router) AllowedMethods ¶
AllowedMethods returns all HTTP verbs registered for a given path across all routing trees.
func (*Router) FindTrailingSlash ¶
FindTrailingSlash tests if an alternate route exists with the opposite trailing slash.
func (*Router) HasPath ¶
HasPath returns true if any HTTP method is registered for the specified path.
func (*Router) Match ¶
Match searches the routing tree for a registered RawHandler matching the HTTP method and path. When matched, extracted path variables are populated into params without heap allocations, and the matched route pattern is returned.
type SSEResponse ¶
SSEResponse encapsulates a Server-Sent Events real-time event stream.
func SSE ¶
func SSE(fn func(sse *SSESender) error) SSEResponse
SSE creates an SSE streaming response handler.
Example ¶
srv.Get("/events", func(ctx context.Context) (sein.SSEResponse, error) {
return sein.SSE(func(sse *sein.SSESender) error {
for i := 0; i < 5; i++ {
_ = sse.SendJSON("tick", map[string]int{"count": i})
time.Sleep(1 * time.Second)
}
return nil
}), nil
})
func (SSEResponse) WithHeader ¶
func (r SSEResponse) WithHeader(key, val string) SSEResponse
WithHeader attaches custom headers to the SSE response.
func (SSEResponse) WriteResponse ¶
func (r SSEResponse) WriteResponse(w http.ResponseWriter) error
WriteResponse satisfies net/http Responder.
type SSESender ¶
type SSESender struct {
// contains filtered or unexported fields
}
SSESender sends Server-Sent Events (SSE) according to the W3C EventSource standard.
RFC Compliance ¶
Conforms to the W3C Server-Sent Events specification (`text/event-stream`).
func NewSSESender ¶
NewSSESender creates an SSESender wrapping the destination network writer.
func (*SSESender) Send ¶
Send emits a simple data-only SSE message.
Example ¶
_ = sse.Send("hello client")
func (*SSESender) SendComment ¶
SendComment emits a comment line (heartbeat/keepalive ping).
func (*SSESender) SendEvent ¶
SendEvent emits a named event with string payload.
Example ¶
_ = sse.SendEvent("price_update", `{"symbol":"BTC","price":98000}`)
type Secret ¶
type Secret[T any] struct { // contains filtered or unexported fields }
Secret wraps sensitive data (passwords, tokens, API keys) to prevent accidental leakage in logs and JSON outputs.
func (Secret[T]) Expose ¶
func (s Secret[T]) Expose() T
Expose returns the raw sensitive value. Synonym for [Value].
func (Secret[T]) MarshalJSON ¶
MarshalJSON safely serializes the secret as a masked string to prevent leakage in API responses.
func (*Secret[T]) UnmarshalJSON ¶
UnmarshalJSON deserializes the raw value into the protected container.
type Server ¶
type Server struct {
RedirectTrailingSlash bool
HandleMethodNotAllowed bool
SkipUnmatchedRoutes bool
Prefork bool
AutoTLSDomains []string
AutoTLSCacheDir string
// contains filtered or unexported fields
}
Server represents a high-throughput, multi-protocol HTTP server engine supporting HTTP/1.1, HTTP/2, HTTP/3 (QUIC), and WebSockets on a single port with zero net/http overhead.
Architectural Context: Zero-Allocation Protocol Matrix ¶
Sein unifies modern IETF protocols into a single event-driven reactor. Incoming requests are routed via a zero-allocation Radix router directly to typed pure handlers without runtime reflection overhead.
Thread Safety ¶
100% thread-safe for concurrent request execution. Configuration methods (e.g. Server.Use, Server.Get) should be called during server setup prior to calling Server.Listen.
Example ¶
srv := sein.New(
sein.WithAddr(":8080"),
sein.WithTrailingSlashRedirect(true),
)
srv.Get("/health", func(ctx context.Context) (string, error) {
return "OK", nil
})
log.Fatal(srv.Listen(":8080"))
func Derive ¶
func Derive[T any](s *Server, fn ResolverFunc[T]) *Server
Derive registers a request-scoped type resolver for type T on the provided server.
func Provide ¶
func Provide[T any](s *Server, fn ResolverFunc[T]) *Server
Provide is an alias for Derive to register a request-scoped dependency provider.
func RegisterResolver ¶
func RegisterResolver[T any](s *Server, fn ResolverFunc[T]) *Server
RegisterResolver is an alias for Derive.
func (*Server) AfterResponse ¶
func (s *Server) AfterResponse(fn AfterResponseHook) *Server
AfterResponse registers a lifecycle hook that executes after every completed HTTP response.
func (*Server) Delete ¶
func (s *Server) Delete(path string, handler any, mw ...Middleware)
Delete registers a route handler on DELETE: accepts any valid handler signature.
func (*Server) DeleteAuth ¶
func (s *Server) DeleteAuth[Res, Auth any](path string, fn func(context.Context, Auth) (Res, error), mw ...Middleware)
DeleteAuth registers a DELETE handler: (ctx, Auth) -> (Res, error)
func (*Server) DeleteWithAuth ¶
func (s *Server) DeleteWithAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), mw ...Middleware)
DeleteWithAuth registers a DELETE handler with request DTO and Auth: (ctx, Req, Auth) -> (Res, error)
func (*Server) DispatchH1 ¶
DispatchH1 dispatches an incoming native H1 request directly through the server's routing and middleware pipeline.
func (*Server) DispatchH2 ¶
func (s *Server) DispatchH2(h2Req *h2engine.ServerRequest, h2Res *h2engine.ServerResponse) error
DispatchH2 is the native zero-net/http HTTP/2 stream request dispatcher.
func (*Server) DispatchH3 ¶
func (s *Server) DispatchH3(h3Req *h3engine.ServerRequest, h3Res *h3engine.ServerResponse) error
DispatchH3 is the native zero-net/http HTTP/3 stream request dispatcher.
func (*Server) Get ¶
func (s *Server) Get(path string, handler any, mw ...Middleware)
Get registers a route handler on GET: accepts any valid handler signature.
func (*Server) GetAuth ¶
func (s *Server) GetAuth[Res, Auth any](path string, fn func(context.Context, Auth) (Res, error), mw ...Middleware)
GetAuth registers a GET handler: (ctx, Auth) -> (Res, error)
func (*Server) GetWithAuth ¶
func (s *Server) GetWithAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), mw ...Middleware)
GetWithAuth registers a GET handler with request DTO and Auth: (ctx, Req, Auth) -> (Res, error)
func (*Server) Group ¶
func (s *Server) Group(prefix string, mw ...Middleware) *Group
Group creates a new scoped router group anchored to this server.
func (*Server) Guard ¶
func (s *Server) Guard(mw ...Middleware) *GuardScope
Guard creates a protected GuardScope on the server with the specified middlewares applied.
func (*Server) Head ¶
func (s *Server) Head(path string, handler any, mw ...Middleware)
Head registers a route handler on HEAD.
func (*Server) ListenAndServe ¶
ListenAndServe starts the native H1 zero-net/http server listening on the configured address.
func (*Server) ListenAndServeAutoTLS ¶
ListenAndServeAutoTLS starts the server with zero-config Let's Encrypt / ACME automatic TLS certificates (RFC 8555 & RFC 8737).
func (*Server) ListenAndServeQUIC ¶
ListenAndServeQUIC starts the native HTTP/3 server over UDP using TLS.
func (*Server) ListenAndServeTLS ¶
ListenAndServeTLS starts listening on s.addr with TLS using native H1 engine.
func (*Server) ListenAndServeUniversal ¶
ListenAndServeUniversal starts the unified multi-protocol engine on port addr (e.g. :443) serving HTTP/1.1, HTTP/2, and WebSockets over TCP, and HTTP/3 (QUIC) over UDP concurrently on the same port.
func (*Server) MapError ¶
func (s *Server) MapError(target error, domainErr DomainError) *Server
MapError registers a mapping from a sentinel error target to a DomainError.
func (*Server) MapErrorFunc ¶
func (s *Server) MapErrorFunc(fn ErrorMapper) *Server
MapErrorFunc registers a custom error mapping predicate.
func (*Server) MapErrors ¶
MapErrors registers multiple domain error mappings from a dictionary table at once.
func (*Server) Mount ¶
func (s *Server) Mount(prefix string, m Module, mw ...Middleware) *Server
Mount attaches a domain Module under the specified prefix with optional group middlewares.
func (*Server) MountModule ¶
MountModule attaches a domain Module directly at root level.
func (*Server) MountRaw ¶
func (s *Server) MountRaw(method, pattern string, handler RawHandler, mw ...Middleware)
MountRaw registers a low-level RawHandler on the specified HTTP method and route pattern.
func (*Server) NoMethod ¶
func (s *Server) NoMethod(handler RawHandler)
NoMethod registers a custom fallback handler for requests where the route path exists but the requested HTTP verb is unsupported (HTTP 405 Method Not Allowed).
func (*Server) NoRoute ¶
func (s *Server) NoRoute(handler RawHandler)
NoRoute registers a custom fallback handler for requests that match no registered routes (HTTP 404).
func (*Server) Options ¶
func (s *Server) Options(path string, handler any, mw ...Middleware)
Options registers a route handler on OPTIONS.
func (*Server) Patch ¶
func (s *Server) Patch(path string, handler any, mw ...Middleware)
Patch registers a route handler on PATCH: accepts any valid handler signature.
func (*Server) PatchAuth ¶
func (s *Server) PatchAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), mw ...Middleware)
PatchAuth registers a PATCH handler: (ctx, Req, Auth) -> (Res, error)
func (*Server) Post ¶
func (s *Server) Post(path string, handler any, mw ...Middleware)
Post registers a route handler on POST: accepts any valid handler signature.
func (*Server) PostAuth ¶
func (s *Server) PostAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), mw ...Middleware)
PostAuth registers a POST handler: (ctx, Req, Auth) -> (Res, error)
func (*Server) PrintRoutes ¶
PrintRoutes formats and returns an ASCII table representation of all registered routes.
func (*Server) Put ¶
func (s *Server) Put(path string, handler any, mw ...Middleware)
Put registers a route handler on PUT: accepts any valid handler signature.
func (*Server) PutAuth ¶
func (s *Server) PutAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), mw ...Middleware)
PutAuth registers a PUT handler: (ctx, Req, Auth) -> (Res, error)
func (*Server) Routes ¶
Routes returns an immutable snapshot list of all registered route patterns and methods in this server.
func (*Server) Serve ¶
Serve starts the native H1 zero-net/http server on the provided net.Listener.
func (*Server) ServeHTTP ¶
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP satisfies the standard http.Handler interface, enabling seamless interoperability with Go stdlib test recorders.
func (*Server) SetTrustedPlatform ¶
SetTrustedPlatform configures the server to trust client IP addresses from specific cloud platform headers.
func (*Server) SetTrustedProxies ¶
SetTrustedProxies configures a list of trusted reverse proxy IP addresses or CIDR subnets.
func (*Server) Shutdown ¶
Shutdown gracefully shuts down all server listeners (TCP H1/H2 and UDP QUIC H3).
func (*Server) Trace ¶
Trace registers a micro-tracing observer callback invoked after every completed request.
func (*Server) Use ¶
func (s *Server) Use(mw ...Middleware)
Use appends global middleware to the server pipeline.
func (*Server) VersionMatrix ¶
func (s *Server) VersionMatrix(prefixFormatter func(version string) string, versions ...string) *VersionGroup
VersionMatrix initializes a multi-version routing matrix with a custom version prefix formatter.
func (*Server) Versioned ¶
func (s *Server) Versioned(versions ...string) *VersionGroup
Versioned initializes a declarative multi-version routing matrix for the specified API versions (e.g. "2", "3" or "v2", "v3"). It maps each version under "/v{ver}" automatically.
type ServerTimingEntry ¶
ServerTimingEntry records a single W3C Server-Timing entry.
type StreamResponse ¶
StreamResponse encapsulates an iterator stream (iter.Seq[T] or channel).
func EventStream ¶
func EventStream[T any](seq iter.Seq[T], eventName ...string) StreamResponse[T]
EventStream creates a Server-Sent Events (SSE) streaming response from an iterator (Go 1.23+ iter.Seq[T]).
func Stream ¶
func Stream[T any](seq iter.Seq[T]) StreamResponse[T]
Stream creates a line-delimited NDJSON streaming response from an iterator (Go 1.23+ iter.Seq[T]).
func (StreamResponse[T]) WithHeader ¶
func (r StreamResponse[T]) WithHeader(key, val string) StreamResponse[T]
WithHeader attaches custom headers to the stream response.
func (StreamResponse[T]) WriteResponse ¶
func (r StreamResponse[T]) WriteResponse(w http.ResponseWriter) error
WriteResponse satisfies net/http Responder.
type StreamWriterResponse ¶
type StreamWriterResponse struct {
Status int
Headers http.Header
WriterFunc func(w io.Writer) error
ContentType string
}
StreamWriterResponse provides streaming chunked output to the client over HTTP/1.1.
func StreamWriter ¶
func StreamWriter(fn func(w io.Writer) error) StreamWriterResponse
StreamWriter creates a streaming response executing fn.
func (StreamWriterResponse) WithContentType ¶
func (s StreamWriterResponse) WithContentType(ct string) StreamWriterResponse
WithContentType sets the Content-Type header on the stream.
func (StreamWriterResponse) WithHeader ¶
func (s StreamWriterResponse) WithHeader(key, val string) StreamWriterResponse
WithHeader attaches custom headers to the streaming response.
func (StreamWriterResponse) WriteResponse ¶
func (s StreamWriterResponse) WriteResponse(w http.ResponseWriter) error
WriteResponse provides compatibility for net/http.
type TraceHook ¶
type TraceHook func(t *TraceInfo)
TraceHook is a callback invoked with granular request execution timings.
type TraceInfo ¶
type TraceInfo struct {
Method string `json:"method"`
Path string `json:"path"`
StatusCode int `json:"status_code"`
ClientIP string `json:"client_ip"`
TotalDuration time.Duration `json:"total_duration"`
}
TraceInfo encapsulates detailed execution metrics across each phase of an HTTP request lifecycle.
type Validatable ¶
type Validatable interface {
Validate() error
}
Validatable is an interface for request DTOs that validate their own invariants. Any DTO implementing Validatable is automatically validated upon decoding.
type VersionGroup ¶
type VersionGroup struct {
// contains filtered or unexported fields
}
VersionGroup represents a scoped view over a VersionMatrix with specific active versions, path prefix, and middlewares.
func (*VersionGroup) Between ¶
func (vg *VersionGroup) Between(minVersion, maxVersion string) *VersionGroup
Between filters active versions to those within the range [minVersion, maxVersion].
func (*VersionGroup) Delete ¶
func (vg *VersionGroup) Delete(path string, handler any, mw ...Middleware)
Delete registers a DELETE route handler across all active versions in this group.
func (*VersionGroup) Do ¶
func (vg *VersionGroup) Do(fn func(g *VersionGroup)) *VersionGroup
Do executes a configuration callback on this VersionGroup.
func (*VersionGroup) Except ¶
func (vg *VersionGroup) Except(versions ...string) *VersionGroup
Except removes the given versions from the active versions list.
func (*VersionGroup) Get ¶
func (vg *VersionGroup) Get(path string, handler any, mw ...Middleware)
Get registers a GET route handler across all active versions in this group.
func (*VersionGroup) Group ¶
func (vg *VersionGroup) Group(prefix string, mw ...Middleware) *VersionGroup
Group creates a nested sub-group under this multi-version group's path prefix.
func (*VersionGroup) Guard ¶
func (vg *VersionGroup) Guard(mw ...Middleware) *VersionGuardScope
Guard creates a protected VersionGuardScope within this multi-version group.
func (*VersionGroup) Head ¶
func (vg *VersionGroup) Head(path string, handler any, mw ...Middleware)
Head registers a HEAD route handler across all active versions in this group.
func (*VersionGroup) MapError ¶
func (vg *VersionGroup) MapError(target error, domainErr DomainError) *VersionGroup
MapError registers a mapping from an internal sentinel error to a Sein domain error.
func (*VersionGroup) MapErrors ¶
func (vg *VersionGroup) MapErrors(errorsMap Errors) *VersionGroup
MapErrors registers multiple error mappings on the multi-version group using an Errors table.
func (*VersionGroup) Mount ¶
func (vg *VersionGroup) Mount(prefix string, m Module, mw ...Middleware) *VersionGroup
Mount attaches a domain Module under this multi-version group.
func (*VersionGroup) Only ¶
func (vg *VersionGroup) Only(versions ...string) *VersionGroup
Only restricts active versions strictly to the given versions list.
func (*VersionGroup) Options ¶
func (vg *VersionGroup) Options(path string, handler any, mw ...Middleware)
Options registers an OPTIONS route handler across all active versions in this group.
func (*VersionGroup) Patch ¶
func (vg *VersionGroup) Patch(path string, handler any, mw ...Middleware)
Patch registers a PATCH route handler across all active versions in this group.
func (*VersionGroup) Post ¶
func (vg *VersionGroup) Post(path string, handler any, mw ...Middleware)
Post registers a POST route handler across all active versions in this group.
func (*VersionGroup) Put ¶
func (vg *VersionGroup) Put(path string, handler any, mw ...Middleware)
Put registers a PUT route handler across all active versions in this group.
func (*VersionGroup) Since ¶
func (vg *VersionGroup) Since(minVersion string) *VersionGroup
Since filters active versions to those greater than or equal to minVersion (v >= minVersion).
func (*VersionGroup) Until ¶
func (vg *VersionGroup) Until(maxVersion string) *VersionGroup
Until filters active versions to those less than or equal to maxVersion (v <= maxVersion).
func (*VersionGroup) Use ¶
func (vg *VersionGroup) Use(mw ...Middleware) *VersionGroup
Use appends middlewares to the multi-version group.
type VersionGuardScope ¶
type VersionGuardScope struct {
*VersionGroup
}
VersionGuardScope represents a protected multi-version scope configured with guards.
func (*VersionGuardScope) Do ¶
func (vgs *VersionGuardScope) Do(fn func(g *VersionGroup)) *VersionGuardScope
Do executes the callback within the protected VersionGuardScope.
func (*VersionGuardScope) MapError ¶
func (vgs *VersionGuardScope) MapError(target error, domainErr DomainError) *VersionGuardScope
MapError registers a domain error mapping rule on the version guard scope.
func (*VersionGuardScope) MapErrors ¶
func (vgs *VersionGuardScope) MapErrors(errorsMap Errors) *VersionGuardScope
MapErrors registers multiple scoped error mappings on the version guard scope.
type VersionMatrix ¶
type VersionMatrix struct {
// contains filtered or unexported fields
}
VersionMatrix manages multi-version routing trees (/v1, /v2, /v3) with declarative lifecycle filters.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
builtin
|
|
|
cache
Package cache provides RFC 7234 HTTP response caching middleware for idempotent routes, with configurable TTL, thread-safe memory storage, Age headers, and tag-based invalidation.
|
Package cache provides RFC 7234 HTTP response caching middleware for idempotent routes, with configurable TTL, thread-safe memory storage, Age headers, and tag-based invalidation. |
|
circuitbreaker
Package circuitbreaker provides fault-tolerance middleware protecting upstream services from cascading downstream failures using a Closed -> Open -> Half-Open state machine.
|
Package circuitbreaker provides fault-tolerance middleware protecting upstream services from cascading downstream failures using a Closed -> Open -> Half-Open state machine. |
|
compress
Package compress provides an ultra-fast, zero-allocation HTTP response compression middleware supporting Zstandard (zstd), Brotli (br), and Gzip.
|
Package compress provides an ultra-fast, zero-allocation HTTP response compression middleware supporting Zstandard (zstd), Brotli (br), and Gzip. |
|
csrf
Package csrf provides Cross-Site Request Forgery (CSRF) mitigation middleware using Double-Submit Cookie validation with constant-time token comparison.
|
Package csrf provides Cross-Site Request Forgery (CSRF) mitigation middleware using Double-Submit Cookie validation with constant-time token comparison. |
|
dump
Package dump provides zero-allocation HTTP request and response inspection middleware, generating detailed debug logs and runnable curl CLI commands.
|
Package dump provides zero-allocation HTTP request and response inspection middleware, generating detailed debug logs and runnable curl CLI commands. |
|
earlydata
Package earlydata provides HTTP/2, HTTP/3, and TLS 1.3 0-RTT Anti-Replay protection complying with RFC 8470 (Using Early Data in HTTP).
|
Package earlydata provides HTTP/2, HTTP/3, and TLS 1.3 0-RTT Anti-Replay protection complying with RFC 8470 (Using Early Data in HTTP). |
|
encryptcookie
Package encryptcookie provides transparent, authenticated AES-256-GCM cookie encryption and decryption middleware for sein HTTP pipelines.
|
Package encryptcookie provides transparent, authenticated AES-256-GCM cookie encryption and decryption middleware for sein HTTP pipelines. |
|
etag
Package etag provides RFC 7232 conditional requests middleware, computing HTTP ETags and short-circuiting unchanged responses with HTTP 304 Not Modified.
|
Package etag provides RFC 7232 conditional requests middleware, computing HTTP ETags and short-circuiting unchanged responses with HTTP 304 Not Modified. |
|
expvar
Package expvar provides standard Go runtime expvar diagnostics middleware, exposing public counters, gauges, maps, and memory stats under /debug/vars.
|
Package expvar provides standard Go runtime expvar diagnostics middleware, exposing public counters, gauges, maps, and memory stats under /debug/vars. |
|
favicon
Package favicon provides zero-allocation favicon serving and log-suppression middleware.
|
Package favicon provides zero-allocation favicon serving and log-suppression middleware. |
|
healthcheck
Package healthcheck provides Kubernetes liveness and readiness probe middleware returning structured JSON health metrics.
|
Package healthcheck provides Kubernetes liveness and readiness probe middleware returning structured JSON health metrics. |
|
helmet
Package helmet provides HTTP security headers middleware designed to harden web applications against common web vulnerabilities, achieving A+ ratings on security scanners.
|
Package helmet provides HTTP security headers middleware designed to harden web applications against common web vulnerabilities, achieving A+ ratings on security scanners. |
|
hostauth
Package hostauth provides HTTP Host header authorization middleware designed to protect against DNS Rebinding, HTTP Host Header Injection, and unauthorized virtual host access.
|
Package hostauth provides HTTP Host header authorization middleware designed to protect against DNS Rebinding, HTTP Host Header Injection, and unauthorized virtual host access. |
|
idempotency
Package idempotency provides HTTP request deduplication and response caching complying with the IETF Idempotency-Key specification (RFC 9457).
|
Package idempotency provides HTTP request deduplication and response caching complying with the IETF Idempotency-Key specification (RFC 9457). |
|
ipfilter
Package ipfilter provides zero-allocation IP address and CIDR subnet access control list (ACL) firewall middleware, supporting granular allow/block list enforcement.
|
Package ipfilter provides zero-allocation IP address and CIDR subnet access control list (ACL) firewall middleware, supporting granular allow/block list enforcement. |
|
jwt
Package jwt provides high-performance, RFC 7519 compliant JSON Web Token authentication middleware supporting HS256/384/512, RS256/384/512, ES256/384/512, and EdDSA (Ed25519) signatures.
|
Package jwt provides high-performance, RFC 7519 compliant JSON Web Token authentication middleware supporting HS256/384/512, RS256/384/512, ES256/384/512, and EdDSA (Ed25519) signatures. |
|
logger
Package logger provides high-throughput, structured HTTP access logging middleware integrated with log.Logger from foundation/async/log.
|
Package logger provides high-throughput, structured HTTP access logging middleware integrated with log.Logger from foundation/async/log. |
|
methodoverride
Package methodoverride provides RFC 3875 HTTP method overriding middleware, allowing clients to override HTTP methods using headers (X-HTTP-Method-Override) or query/form parameters (_method).
|
Package methodoverride provides RFC 3875 HTTP method overriding middleware, allowing clients to override HTTP methods using headers (X-HTTP-Method-Override) or query/form parameters (_method). |
|
pagination
Package pagination provides zero-allocation API request pagination, limit bounding, offset calculation, sorting extraction, and response metadata builder utilities.
|
Package pagination provides zero-allocation API request pagination, limit bounding, offset calculation, sorting extraction, and response metadata builder utilities. |
|
pprof
Package pprof provides Go runtime profiling endpoints under /debug/pprof/ for live production performance inspection and memory leak analysis.
|
Package pprof provides Go runtime profiling endpoints under /debug/pprof/ for live production performance inspection and memory leak analysis. |
|
prefork
Package prefork provides high-throughput multi-process clustering utilizing SO_REUSEPORT.
|
Package prefork provides high-throughput multi-process clustering utilizing SO_REUSEPORT. |
|
proxy
Package proxy provides high-throughput HTTP reverse proxy and load balancing middleware forwarding requests to upstream backend servers.
|
Package proxy provides high-throughput HTTP reverse proxy and load balancing middleware forwarding requests to upstream backend servers. |
|
recover
Package recover provides panic recovery middleware for sein HTTP pipelines.
|
Package recover provides panic recovery middleware for sein HTTP pipelines. |
|
responsetime
Package responsetime provides HTTP response latency measurement middleware injecting X-Response-Time and W3C Server-Timing headers.
|
Package responsetime provides HTTP response latency measurement middleware injecting X-Response-Time and W3C Server-Timing headers. |
|
revision
Package revision provides application version, Git commit hash, and build timestamp metadata injection middleware and /version diagnostic endpoint.
|
Package revision provides application version, Git commit hash, and build timestamp metadata injection middleware and /version diagnostic endpoint. |
|
rewrite
Package rewrite provides URL path and query rewriting middleware for backward compatibility, legacy URL translation, and clean API routing.
|
Package rewrite provides URL path and query rewriting middleware for backward compatibility, legacy URL translation, and clean API routing. |
|
session
Package session provides high-performance, thread-safe HTTP session management supporting in-memory storage, flash messages, and secure cookie lifecycle binding.
|
Package session provides high-performance, thread-safe HTTP session management supporting in-memory storage, flash messages, and secure cookie lifecycle binding. |
|
skip
Package skip provides conditional execution wrapper middleware.
|
Package skip provides conditional execution wrapper middleware. |
|
timeout
Package timeout provides request execution deadline middleware, returning HTTP 504 Gateway Timeout when handler processing exceeds the allotted time boundary.
|
Package timeout provides request execution deadline middleware, returning HTTP 504 Gateway Timeout when handler processing exceeds the allotted time boundary. |
|
Package grpc provides a compact, zero-allocation, high-performance gRPC server engine for Go.
|
Package grpc provides a compact, zero-allocation, high-performance gRPC server engine for Go. |
|
codes
Package codes defines the standard canonical status codes used by gRPC.
|
Package codes defines the standard canonical status codes used by gRPC. |
|
metadata
Package metadata provides gRPC key-value metadata management for requests and responses.
|
Package metadata provides gRPC key-value metadata management for requests and responses. |
|
status
Package status implements gRPC status errors and conversions.
|
Package status implements gRPC status errors and conversions. |
|
internal
|
|
|
compress/brotli/matchfinder
The matchfinder package defines reusable components for data compression.
|
The matchfinder package defines reusable components for data compression. |
|
compress/flate
Package flate implements the DEFLATE compressed data format, described in RFC 1951.
|
Package flate implements the DEFLATE compressed data format, described in RFC 1951. |
|
compress/fse
Package fse provides Finite State Entropy encoding and decoding.
|
Package fse provides Finite State Entropy encoding and decoding. |
|
compress/huff0
amd64 stubs and dispatch for the asm loops used by decompress_asm.go.
|
amd64 stubs and dispatch for the asm loops used by decompress_asm.go. |
|
compress/zstd
Package zstd provides encoding and decoding of zstandard files and streams.
|
Package zstd provides encoding and decoding of zstandard files and streams. |
|
qpack
Package qpack implements QPACK: Field Compression for HTTP/3 (RFC 9204).
|
Package qpack implements QPACK: Field Compression for HTTP/3 (RFC 9204). |
|
quic/internal/mocks
Package mocks is a generated GoMock package.
|
Package mocks is a generated GoMock package. |
|
quic/internal/mocks/ackhandler
Package mockackhandler is a generated GoMock package.
|
Package mockackhandler is a generated GoMock package. |
|
quic/internal/monotime
Package monotime provides a monotonic time representation that is useful for measuring elapsed time.
|
Package monotime provides a monotonic time representation that is useful for measuring elapsed time. |
|
quic/internal/ossfuzzseeds
Package ossfuzzseeds writes Go native fuzz seeds as OSS-Fuzz seed corpus files.
|
Package ossfuzzseeds writes Go native fuzz seeds as OSS-Fuzz seed corpus files. |
|
quic/internal/utils/linkedlist
Package list implements a doubly linked list.
|
Package list implements a doubly linked list. |
|
quic/testutils
Package testutils contains utilities for simulating packet injection and man-in-the-middle (MITM) attacker tests.
|
Package testutils contains utilities for simulating packet injection and man-in-the-middle (MITM) attacker tests. |
|
Package preset provides ready-to-use production server presets and consolidated middleware suites, allowing applications to configure enterprise security, metrics, and compression with a single import.
|
Package preset provides ready-to-use production server presets and consolidated middleware suites, allowing applications to configure enterprise security, metrics, and compression with a single import. |
|
tunnel
|
|
|
inbound
Package inbound provides a high-performance, mixed SOCKS5 and HTTP/HTTPS inbound proxy server.
|
Package inbound provides a high-performance, mixed SOCKS5 and HTTP/HTTPS inbound proxy server. |
|
ssh/server
Package server provides a customizable, high-performance SSH server implementation.
|
Package server provides a customizable, high-performance SSH server implementation. |
|
x
|
|
|
cron
Package cron provides a zero-allocation, in-memory background cron task scheduler for sein.
|
Package cron provides a zero-allocation, in-memory background cron task scheduler for sein. |
|
crud
Package crud provides automated RESTful CRUD endpoint mounting for generic repositories (e.g.
|
Package crud provides automated RESTful CRUD endpoint mounting for generic repositories (e.g. |
|
html
Package html provides zero-allocation HTML component rendering and native HTMX integration for sein.
|
Package html provides zero-allocation HTML component rendering and native HTMX integration for sein. |
|
loadshed
Package loadshed provides adaptive load shedding and concurrency-limiting middleware protecting backend services from thundering herds, latency spikes, and out-of-memory crashes.
|
Package loadshed provides adaptive load shedding and concurrency-limiting middleware protecting backend services from thundering herds, latency spikes, and out-of-memory crashes. |
|
monitor
Package monitor provides a lightweight, zero-dependency real-time server dashboard displaying CPU, memory, goroutines, GC pauses, and RPS metrics in the browser.
|
Package monitor provides a lightweight, zero-dependency real-time server dashboard displaying CPU, memory, goroutines, GC pauses, and RPS metrics in the browser. |
|
openapi
Package openapi provides automated OpenAPI 3.1.0 document generation, DTO reflection, and interactive Scalar UI for sein.
|
Package openapi provides automated OpenAPI 3.1.0 document generation, DTO reflection, and interactive Scalar UI for sein. |
|
otel
Package otel provides a zero-dependency, ultra-high-performance server-side OpenTelemetry (OTel) distributed tracing engine strictly conforming to W3C TraceContext and OTLP/HTTP specifications.
|
Package otel provides a zero-dependency, ultra-high-performance server-side OpenTelemetry (OTel) distributed tracing engine strictly conforming to W3C TraceContext and OTLP/HTTP specifications. |
|
paseto
Package paseto provides Platform-Agnostic Security Tokens (PASETO v4.public and v4.local) authentication and cryptographic verification middleware.
|
Package paseto provides Platform-Agnostic Security Tokens (PASETO v4.public and v4.local) authentication and cryptographic verification middleware. |
|
prometheus
Package prometheus provides zero-dependency Prometheus metrics collection and exposition middleware, serving request latency histograms, status code counters, and runtime gauges on /metrics.
|
Package prometheus provides zero-dependency Prometheus metrics collection and exposition middleware, serving request latency histograms, status code counters, and runtime gauges on /metrics. |
|
sentry
Package sentry provides lightweight, zero-dependency Sentry error monitoring and reporting middleware.
|
Package sentry provides lightweight, zero-dependency Sentry error monitoring and reporting middleware. |
|
socketio
Package socketio provides a high-throughput, RFC-compliant Socket.IO v5 and Engine.IO v4 server for the sein framework.
|
Package socketio provides a high-throughput, RFC-compliant Socket.IO v5 and Engine.IO v4 server for the sein framework. |
|
swaggerui
Package swaggerui provides zero-dependency interactive Swagger UI / OpenAPI documentation serving.
|
Package swaggerui provides zero-dependency interactive Swagger UI / OpenAPI documentation serving. |