sein

package module
v0.0.0-...-6f71106 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2026 License: BSD-3-Clause Imports: 44 Imported by: 0

README

sein

Server Network Stack & Web Framework for Go

«In backends, madness is the default. Let sein be your light of sanity.»

Go Version Go Reference License Zero-Alloc Single-Port Matrix Ecosystem

sein is a server network stack and web framework for Go. It supports running HTTP/1.1, HTTP/2, HTTP/3 (QUIC), WebSockets, and gRPC on a single port :443 without reverse proxies, with universal handler compilation, contract-first DTO binding, and table-driven domain error mapping.

English • РусскийArchitecture Concept

Installation

sein requires Go version 1.27 or higher.

go get github.com/lemon4ksan/sein

Quickstart

Universal handlers, declarative validation, and zero-glue domain routing:

package main

import (
	"context"
	"log"

	"github.com/google/uuid"
	"github.com/lemon4ksan/sein"
)

// 1. Declare DTO contract with sanitization & validation
type UpdateUserDTO struct {
	UserID   uuid.UUID `path:"id" validate:"uuid"`
	Username string    `json:"username" validate:"required,min=3,max=30" sanitize:"trim"`
	Email    string    `json:"email" validate:"required,email" sanitize:"lower"`
	Role     string    `query:"role,default=user" validate:"enum=user|admin|moderator"`
	Auth     string    `auth:"bearer,required"`
}

type UserResponse struct {
	ID       string `json:"id"`
	Username string `json:"username"`
	Email    string `json:"email"`
	Role     string `json:"role"`
}

func main() {
	srv := sein.New(
		sein.WithAddr(":8080"),
		sein.WithTrailingSlashRedirect(true),
		sein.WithMethodNotAllowed(true),
	)

	// 2. Universal Handlers: pass pure Go functions directly
	srv.Get("/health", func(ctx context.Context) (string, error) {
		return "OK", nil
	})

	srv.Post("/users/:id", func(ctx context.Context, req UpdateUserDTO) (*UserResponse, error) {
		return &UserResponse{
			ID:       req.UserID.String(),
			Username: req.Username,
			Email:    req.Email,
			Role:     req.Role,
		}, nil
	})

	// 3. Server-Sent Events (SSE)
	srv.Get("/events", func(ctx context.Context) (sein.SSEResponse, error) {
		return sein.SSE(func(sse *sein.SSESender) error {
			_ = sse.SendJSON("connected", map[string]string{"status": "online"})
			return nil
		}), nil
	})

	log.Println("sein listening on http://localhost:8080")
	log.Fatal(srv.Listen(":8080"))
}

Universal Routing & Zero-Glue Architecture

sein features a universal handler compiler: standard HTTP verbs (Get, Post, Patch, Delete, Put) accept any pure Go function signature without requiring framework-specific glue wrappers.

1. Supported Handler Signatures
Purpose Handler Signature Data Extraction Return Value
Action func(ctx context.Context) error None (context only) 200 OK on nil
Query func(ctx context.Context) (Res, error) None (context only) JSON response
Direct Path ID func(ctx context.Context, id ID) (Res, error) URL parameter :id (Snowflake, uint64, string, UUID) JSON response
Path ID Action func(ctx context.Context, id ID) error URL parameter :id 200 OK on nil
DTO Payload func(ctx context.Context, req DTO) (Res, error) DTO (JSON Body / Query / Headers) JSON response
ID + Body Payload func(ctx context.Context, id ID, req DTO) (Res, error) :id from URL + JSON Body JSON response
Raw Request func(req *sein.Request) (Res, error) Direct request access JSON response
2. Zero-Glue Controllers (Service Method Promotion)

Because sein handler signatures match standard domain service signatures, you can embed services into modules/controllers and mount methods directly:

type BotController struct {
	*bots.Service // Auto-promotes Create, Get, Delete, Update, etc.
}

func (c *BotController) Mount(g *sein.Group) {
	// Table-driven domain error mapping
	g.MapErrors(sein.Errors{
		database.ErrNotFound:       ErrBotNotFound,
		bots.ErrInvalidUserID:      ErrInvalidBotUserID,
		bots.ErrActiveBot:          ErrBotActiveCannotDelete,
		bots.ErrAlreadyLinkedAccount: ErrBotAlreadyLinkedAccount,
	})

	// Direct service method binding with ZERO forwarding shims
	g.Post("", c.Create)
	g.Get("/:id", c.Get)
	g.Patch("/:id", c.Update)       // Takes (ctx, id Snowflake, payload UpdatePayload)
	g.Patch("/:id/type", c.SetType)
	g.Delete("/:id", c.Delete)
	g.Post("/:id/disconnect", c.Disconnect) // Takes (ctx, id Snowflake) error
}
3. Table-Driven Domain Error Mapping

Map internal sentinel errors to typed HTTP domain errors declaratively using sein.Errors:

var (
	ErrUserNotFound = sein.NotFound("USER_NOT_FOUND", "User does not exist")
	ErrBusyEmail    = sein.Conflict("EMAIL_EXISTS", "Email is already taken")
)

users.MapErrors(sein.Errors{
	database.ErrNotFound:  ErrUserNotFound,
	users.ErrEmailTaken:   ErrBusyEmail,
})

DTO Structs & Declarative Validation

Declare all request inputs (path, query, headers, cookies, JSON payload) in a unified DTO struct with automatic validation and sanitization:

type UpdateProfileDTO struct {
	// Protocol Data Sources
	UserID      uuid.UUID           `path:"user_id" validate:"uuid"`       // URL Path: /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 bounds
	Tags        []string            `query:"tags,sep=|"`                   // Slice with custom separator
	TraceID     string              `header:"X-Trace-ID" validate:"required"` // HTTP Header
	SessionID   string              `cookie:"session_id" validate:"required"` // HTTP Cookie
	AuthToken   string              `auth:"bearer,required"`               // Authorization: Bearer <token>
	ClientIP    net.IP              `net:"ip"`                             // Resolved Client IP
	Avatar      *sein.File          `file:"avatar,required"`               // Uploaded File
	Gallery     []*sein.File        `files:"gallery"`                      // Multiple Uploaded Files
	Password    sein.Secret[string] `json:"password" validate:"min=8"`     // Masked in logs & stack traces
	UserSession *Session            `ctx:""`                               // Typed context session
	Bio         string              `json:"bio" validate:"max=500" sanitize:"squish"` // Collapsed whitespace
}
📋 Tag Directives Reference
Category Directive Description Example
Sources path:"key" URL path parameter (/users/:id) path:"id"
query:"key" URL query parameter (?page=1) query:"page,default=1"
header:"key" HTTP request header header:"X-API-Key"
cookie:"key" HTTP cookie value cookie:"session_id"
auth:"bearer" Extracts Authorization: Bearer <token> auth:"bearer,required"
form:"key" Form field value (multipart or urlencoded) form:"title"
file:"key" Single uploaded multipart file (*sein.File) file:"avatar,required"
files:"key" Multiple uploaded multipart files ([]*sein.File) files:"attachments"
json:"key" JSON request body payload field json:"name"
net:"ip" Resolved remote client IP address net:"ip"
ctx:"" Typed inline context injection ctx:""
Sanitizers (sanitize:"...") trim Strips leading and trailing whitespace sanitize:"trim"
lower Converts ASCII characters to lowercase sanitize:"lower"
upper Converts ASCII characters to uppercase sanitize:"upper"
squish Collapses multiple consecutive whitespaces sanitize:"squish"
digits_only Extracts digits only from string sanitize:"digits_only"
Validation (validate:"...") required Field must be present and non-zero validate:"required"
min=N / max=N String length bounds or numeric ranges validate:"min=8,max=64"
enum=a|b|c Allowed value set validation validate:"enum=asc|desc"
email Validates standard email address format validate:"email"
uuid Validates UUID format (RFC 4122 / RFC 9562) validate:"uuid"
pattern=regex Matches precompiled regular expression validate:"pattern=^[A-Z0-9]+$"

Configuration Presets

Quick initialization of middleware stacks for production:

import "github.com/lemon4ksan/sein/preset"

// Production preset includes: Panic Recovery, Security Headers, CORS, RequestID,
// Prometheus metrics (/system/metrics), Health Checks (/system/health), and Revision (/system/version)
app := preset.Production(
	preset.WithPrometheus("/system/metrics"),
	preset.WithRevision("v1.2.0", "/system/version"),
	preset.WithCORS(preset.CORSConfig{
		AllowOrigins: []string{"https://example.com"},
	}),
)

⚡ Performance Profile

1. Network Throughput Benchmark (TechEmpower Round 22, 32 Cores, 10GbE):
Framework Language / Runtime Network Engine Throughput Relative to Gin
Nest Node.js HTTP parser 105,064 reqs/s 0.15x
Express Node.js HTTP parser 113,117 reqs/s 0.16x
Fastify Node.js fast-json 415,600 reqs/s 0.61x
Spring Java Netty / NIO 506,087 reqs/s 0.75x
Gin Go net/http 676,019 reqs/s 1.00x (Base)
Elysia Bun (C++/JS) uWebSockets (C++) 2,454,631 reqs/s 3.63x
Sein (Native H1 Net) Go Native H1 Engine ~3,200,000+* reqs/s 4.73x
Sein (In-Memory Core) Go SIMD Fast H1 Core 21,291,486* reqs/s 31.50x

* Local results. Not tested on an actual server.

2. OS TCP Socket Comparison (Loopback)

Tested over OS TCP stack with keep-alive connections (net.Listen + net.Dial):

cpu: 12th Gen Intel(R) Core(TM) i5-12400F (12 Threads)
BenchmarkTechEmpower_RealTCPSocket_Sein-12       3,056 ns/op   178 B/op    7 allocs/op   (~330,000 req/s per socket)
BenchmarkTechEmpower_RealTCPSocket_StdHTTP-12    4,716 ns/op  2,252 B/op   20 allocs/op   (~210,000 req/s per socket)

License

sein is distributed under the BSD-3-Clause License.

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

Examples

Constants

This section is empty.

Variables

View Source
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)

View Source
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

func AddTiming(ctx context.Context, name string, dur time.Duration, description ...string)

AddTiming records a named duration on the active request in ctx for the W3C Server-Timing header.

func Defer

func Defer(ctx context.Context, fn func())

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

func Get[T any](r *Request) (T, bool)

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

func IngestDTO[T any](req *Request, dest *T) error

IngestDTO extracts multi-source request data (Path, Query, Headers, Cookies, Auth, Net, Form, Files, Context, Body) into dest.

func MustGet

func MustGet[T any](r *Request) T

MustGet retrieves a typed value from request storage, panicking if the value was not set.

Example

session := sein.MustGet[*UserSession](req)

func Set

func Set[T any](r *Request, val T)

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

func SignCookieValue(value string, secret string) string

SignCookieValue generates a signed cookie value in "value.signature" format using HMAC-SHA256.

func StartTimer

func StartTimer(ctx context.Context, name string, description ...string) func()

StartTimer starts a named W3C Server-Timing stopwatch on the active request in ctx, returning a stop callback.

func ValidateRouteBinding

func ValidateRouteBinding[T any](routePath string)

ValidateRouteBinding checks at server startup that all URL path parameters declared in path have corresponding bindings in the DTO type T.

func ValidateRouteBindingType

func ValidateRouteBindingType(typ reflect.Type, routePath string)

ValidateRouteBindingType checks at server startup that all URL path parameters declared in path have corresponding bindings in typ.

func VerifyCookieValue

func VerifyCookieValue(signedValue string, secret string) (string, bool)

VerifyCookieValue verifies a "value.signature" string against secret using HMAC-SHA256 with constant-time equality.

func WithValue

func WithValue[T any](ctx context.Context, val T) context.Context

WithValue injects a typed value into a context so it can be resolved by type-directed handlers.

Types

type AfterResponseHook

type AfterResponseHook func(req *Request, statusCode int, duration time.Duration)

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

type DirectH1Responder interface {
	WriteToH1(res *h1engine.Response) error
}

DirectH1Responder is an interface for direct serialization to the native H1 response.

type DomainError

type DomainError interface {
	error
	HTTPStatus() int
	ErrorCode() string
}

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.

func E

func E(from error, to DomainError) ErrorMap

E constructs an ErrorMap translation pair.

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) Bytes

func (f *File) Bytes() ([]byte, error)

Bytes reads and caches the full uploaded file content into memory.

func (*File) Open

func (f *File) Open() (io.ReadCloser, error)

Open opens the underlying uploaded file stream for reading.

func (*File) SaveTo

func (f *File) SaveTo(dstPath string) error

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) Derive

func (g *Group) Derive(t reflect.Type, fn any) *Group

Derive registers a request-scoped type resolver for type T on this group.

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

func (g *Group) MapErrors(errorsMap Errors) *Group

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.

func (*Group) PutAuth

func (g *Group) PutAuth[Req, Res, Auth any](path string, fn func(context.Context, Req, Auth) (Res, error), mw ...Middleware)

PutAuth registers a PUT handler on a group: (ctx, Req, Auth) -> (Res, error)

func (*Group) Use

func (g *Group) Use(mw ...Middleware)

Use appends middlewares to the group.

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

func AsHTTPError(err error) (HTTPError, bool)

AsHTTPError checks if an error wraps or is an HTTPError.

func ErrBadRequest

func ErrBadRequest(message string, cause ...error) HTTPError

ErrBadRequest creates a 400 Bad Request ad-hoc error.

func ErrConflict

func ErrConflict(message string, cause ...error) HTTPError

ErrConflict creates a 409 Conflict ad-hoc error.

func ErrForbidden

func ErrForbidden(message string, cause ...error) HTTPError

ErrForbidden creates a 403 Forbidden ad-hoc error.

func ErrGatewayTimeout

func ErrGatewayTimeout(message string, cause ...error) HTTPError

ErrGatewayTimeout creates a 504 Gateway Timeout ad-hoc error.

func ErrInternal

func ErrInternal(message string, cause ...error) HTTPError

ErrInternal creates a 500 Internal Server Error ad-hoc error.

func ErrNotFound

func ErrNotFound(message string, cause ...error) HTTPError

ErrNotFound creates a 404 Not Found ad-hoc error.

func ErrRequestEntityTooLarge

func ErrRequestEntityTooLarge(message string, cause ...error) HTTPError

ErrRequestEntityTooLarge creates a 413 Request Entity Too Large ad-hoc error.

func ErrTooEarly

func ErrTooEarly(message string, cause ...error) HTTPError

ErrTooEarly creates a 425 Too Early ad-hoc error (RFC 8470).

func ErrTooManyRequests

func ErrTooManyRequests(message string, cause ...error) HTTPError

ErrTooManyRequests creates a 429 Too Many Requests ad-hoc error.

func ErrUnauthorized

func ErrUnauthorized(message string, cause ...error) HTTPError

ErrUnauthorized creates a 401 Unauthorized ad-hoc error.

func ErrUnprocessable

func ErrUnprocessable(message string, cause ...error) HTTPError

ErrUnprocessable creates a 422 Unprocessable Entity ad-hoc error.

func NewError

func NewError(status int, message string, cause ...error) HTTPError

NewError creates a custom semantic HTTPError.

func NewHTTPError

func NewHTTPError(status int, code, message string) HTTPError

NewHTTPError creates a structured HTTPError with status, code, and message.

func (HTTPError) Error

func (e HTTPError) Error() string

func (HTTPError) ErrorCode

func (e HTTPError) ErrorCode() string

func (HTTPError) HTTPStatus

func (e HTTPError) HTTPStatus() int

func (HTTPError) StatusCode

func (e HTTPError) StatusCode() int

func (HTTPError) Unwrap

func (e HTTPError) Unwrap() error

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

func BearerAuth[T any](validator func(ctx context.Context, token string) (T, error)) Middleware

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

func WithAddr(addr string) Option

WithAddr configures the default listening network address (e.g. ":8080" or "0.0.0.0:443").

func WithAutoTLS

func WithAutoTLS(domains ...string) Option

WithAutoTLS configures zero-config automatic TLS certificate provisioning via ACME (Let's Encrypt / ZeroSSL).

func WithAutoTLSCacheDir

func WithAutoTLSCacheDir(dir string) Option

WithAutoTLSCacheDir configures the directory used to persist ACME certificates on disk.

func WithCookieSecret

func WithCookieSecret(secret string) Option

WithCookieSecret configures a default secret key for HMAC signed cookie verification.

func WithMethodNotAllowed

func WithMethodNotAllowed(enabled bool) Option

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

func WithPrefork(enabled bool) Option

WithPrefork enables high-load multi-process socket preforking on UNIX systems (`SO_REUSEPORT`).

func WithSkipUnmatchedRoutes

func WithSkipUnmatchedRoutes(enabled bool) Option

WithSkipUnmatchedRoutes configures whether global middlewares are bypassed for unmatched routes (404 / 405).

func WithTrailingSlashRedirect

func WithTrailingSlashRedirect(enabled bool) Option

WithTrailingSlashRedirect configures whether requests with mismatched trailing slashes are automatically redirected (RFC 9110 §15.4.2).

func WithTrustedPlatform

func WithTrustedPlatform(headerName string) Option

WithTrustedPlatform sets a trusted platform header (e.g. "CF-Connecting-IP") for ClientIP extraction.

func WithTrustedProxies

func WithTrustedProxies(proxies []string) Option

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 ParamSlot

type ParamSlot struct {
	Key   string
	Value string
}

ParamSlot represents a key-value path parameter pair without heap allocation.

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) String

func (p ParamValue) String() string

String returns the raw string value.

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.

func (*Params) Find

func (p *Params) Find(key string) (string, bool)

Find returns the value of key and true if found.

func (*Params) Get

func (p *Params) Get(key string) string

Get returns the value of the parameter with key, or empty string if not found.

func (*Params) Len

func (p *Params) Len() int

Len returns the number of parameters.

func (*Params) Map

func (p *Params) Map() map[string]string

Map returns a copy of parameters as a map[string]string for compatibility.

func (*Params) Reset

func (p *Params) Reset()

Reset clears all parameters.

func (*Params) Set

func (p *Params) Set(key, value string)

Set sets a key-value parameter pair.

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

type RawHandler func(req *Request) (any, error)

RawHandler is the internal uniform handler signature returning any payload or error.

type RedirectError

type RedirectError struct {
	TargetURL string
	Status    int
}

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

func FromContext(ctx context.Context) (*Request, bool)

FromContext retrieves the active *Request associated with the context, if present.

func NewH1Request

func NewH1Request(h1Req *h1engine.Request, params ...*Params) *Request

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

func NewRequest(r *http.Request, params ...*Params) *Request

NewRequest creates a Request wrapping a standard http.Request.

func (*Request) AddTiming

func (r *Request) AddTiming(name string, dur time.Duration, description ...string)

AddTiming records an explicit execution duration for the W3C Server-Timing header (e.g. database query, redis, auth).

func (*Request) AllocBytes

func (r *Request) AllocBytes(size int) []byte

AllocBytes allocates a zero-copy byte slice of the requested size out of the per-request arena.

func (*Request) AllocString

func (r *Request) AllocString(s string) string

AllocString clones a string into the contiguous per-request arena buffer without heap allocation.

func (*Request) Arena

func (r *Request) Arena() *borrow.Scope

Arena is an alias for Scope, providing a per-request bump allocator with zero GC overhead.

func (*Request) BearerToken

func (r *Request) BearerToken() (string, bool)

BearerToken extracts the token from the "Authorization: Bearer <token>" header.

func (*Request) Bind

func (r *Request) Bind(dest any) error

Bind ingests the request path parameters, query parameters, headers, and payload into dest using the precompiled binder.

func (*Request) BindJSON

func (r *Request) BindJSON(dest any) error

BindJSON decodes the JSON request body into dest and executes automatic validation if dest implements Validatable.

func (*Request) Body

func (r *Request) Body() []byte

Body reads and caches the full request body, automatically decompressing if Content-Encoding is present.

func (*Request) ClientIP

func (r *Request) ClientIP() string

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

func (r *Request) ClientIPWithTrust(trustedProxies []netip.Prefix) string

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

func (r *Request) Context() context.Context

Context returns the request-scoped context, automatically binding the active *Request.

func (*Request) Cookie

func (r *Request) Cookie(name string) (string, error)

Cookie retrieves a cookie value by name.

func (*Request) CookieSecret

func (r *Request) CookieSecret() string

CookieSecret returns the secret key used for signed cookie verification on this request.

func (*Request) Cookies

func (r *Request) Cookies() []*http.Cookie

Cookies parses and returns the HTTP cookies sent with the 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) DelHeader

func (r *Request) DelHeader(key string)

DelHeader removes a request header.

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

func (r *Request) EarlyHints(headers http.Header) error

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 (r *Request) EarlyHintsLinks(links ...string) error

EarlyHintsLinks emits 103 Early Hints preloading links (e.g. "</style.css>; rel=preload; as=style").

func (*Request) FormFile

func (r *Request) FormFile(key string) (*File, error)

FormFile retrieves an uploaded file from multipart form data.

func (*Request) FormFiles

func (r *Request) FormFiles(key string) ([]*File, error)

FormFiles retrieves all uploaded files under key from multipart form data.

func (*Request) FormValue

func (r *Request) FormValue(key string) string

FormValue retrieves a value from POST/PUT form-encoded or multipart data.

func (*Request) Header

func (r *Request) Header(key string) string

Header retrieves an HTTP request header by key.

func (*Request) Hijack

func (r *Request) Hijack() (net.Conn, *bufio.ReadWriter, error)

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) Host

func (r *Request) Host() string

Host returns the request target host (Host header or URL host).

func (*Request) IP

func (r *Request) IP() string

IP returns the real client IP address.

func (*Request) IPs

func (r *Request) IPs() []string

IPs returns all IP addresses from the X-Forwarded-For chain in order.

func (*Request) IfModifiedSince

func (r *Request) IfModifiedSince(lastModified time.Time) bool

IfModifiedSince reports whether the resource has not been modified since the client's header timestamp (RFC 7232 §3.3).

func (*Request) IfNoneMatch

func (r *Request) IfNoneMatch(etag string) bool

IfNoneMatch reports whether the client's If-None-Match header matches etag (RFC 7232 §3.2).

func (*Request) Method

func (r *Request) Method() string

Method returns the HTTP method (e.g. GET, POST).

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) ParamMap

func (r *Request) ParamMap() map[string]string

ParamMap returns a copy of path parameters as a map for compatibility.

func (*Request) Params

func (r *Request) Params() *Params

Params returns the underlying zero-alloc Params struct.

func (*Request) Path

func (r *Request) Path() string

Path returns the requested URL path.

func (*Request) Proto

func (r *Request) Proto() string

Proto returns the HTTP protocol version (e.g. "HTTP/1.1", "HTTP/2.0", "HTTP/3.0").

func (*Request) Protocol

func (r *Request) Protocol() string

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

func (r *Request) Raw() *http.Request

Raw returns the underlying *http.Request for advanced compatibility if available.

func (*Request) RawBody

func (r *Request) RawBody() []byte

RawBody returns the raw, un-decompressed request payload bytes.

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

func (r *Request) RemoteAddr() string

RemoteAddr returns the raw remote network address (IP:port).

func (*Request) RoutePattern

func (r *Request) RoutePattern() string

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

func (r *Request) SaveUploadedFile(file *File, dstPath string) error

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

func (r *Request) Scheme() string

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

func (r *Request) Scope() *borrow.Scope

Scope returns the request-scoped lexical arena, guaranteed to be recycled with 0 GC allocations on request finish.

func (*Request) ServerTimingHeader

func (r *Request) ServerTimingHeader() string

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) SetBody

func (r *Request) SetBody(body []byte)

SetBody overrides the request payload buffer.

func (*Request) SetContext

func (r *Request) SetContext(ctx context.Context)

SetContext sets a new context on the request.

func (*Request) SetCookieSecret

func (r *Request) SetCookieSecret(secret string)

SetCookieSecret sets the secret key used for signed cookie verification on this request.

func (*Request) SetHeader

func (r *Request) SetHeader(key, val string)

SetHeader sets or replaces a request header value.

func (*Request) SetMethod

func (r *Request) SetMethod(method string)

SetMethod sets or rewrites the HTTP request method.

func (*Request) SetPath

func (r *Request) SetPath(path string)

SetPath sets or rewrites the requested URL path.

func (*Request) SetQuery

func (r *Request) SetQuery(query string)

SetQuery sets or rewrites the raw query string.

func (*Request) SetRoutePattern

func (r *Request) SetRoutePattern(pattern string)

SetRoutePattern manually sets the route pattern for custom request dispatching.

func (*Request) StartTimer

func (r *Request) StartTimer(name string, description ...string) func()

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()

func (*Request) WithContext

func (r *Request) WithContext(ctx context.Context) *Request

WithContext sets a new context on the request.

type ResolverFunc

type ResolverFunc[T any] func(req *Request) (T, error)

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

type Response[T any] struct {
	Status  int
	Body    T
	Headers http.Header
	Cookies []*http.Cookie
}

Response is a type-safe HTTP response container carrying status, headers, and body.

func Accepted

func Accepted[T any](body T) Response[T]

Accepted creates a type-safe 202 Accepted Response for asynchronous background processing (RFC 9110 §15.3.3).

func Created

func Created[T any](body T) Response[T]

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 HTML

func HTML(content string) Response[string]

HTML creates an HTML response setting Content-Type to `text/html; charset=utf-8`.

func NoContent

func NoContent() Response[any]

NoContent creates a type-safe 204 No Content Response with an empty wire payload (RFC 9110 §15.3.5).

func NotModified

func NotModified() Response[any]

NotModified creates a 304 Not Modified conditional cache Response (RFC 9110 §15.4.5).

func OK

func OK[T any](body T) Response[T]

OK creates a type-safe 200 OK Response wrapping body.

Example

return sein.OK(User{ID: 1, Name: "Alice"}), nil

func Redirect

func Redirect(targetURL string, status ...int) Response[any]

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

func RedirectTo[T any](targetURL string, status ...int) Response[T]

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

func StatusWith[T any](status int, body T, headers http.Header) Response[T]

StatusWith creates a response with custom HTTP status code, body, and headers.

func (Response[T]) ResponseBody

func (r Response[T]) ResponseBody() any

ResponseBody returns the generic body payload.

func (Response[T]) ResponseCookies

func (r Response[T]) ResponseCookies() []*http.Cookie

ResponseCookies returns attached cookies.

func (Response[T]) ResponseHeaders

func (r Response[T]) ResponseHeaders() http.Header

ResponseHeaders returns the response headers map.

func (Response[T]) StatusCode

func (r Response[T]) StatusCode() int

StatusCode returns the HTTP status code.

func (Response[T]) WithCookie

func (r Response[T]) WithCookie(c *http.Cookie) Response[T]

WithCookie attaches a set-cookie instruction to the response.

func (Response[T]) WithETag

func (r Response[T]) WithETag(etag string) Response[T]

WithETag sets the ETag header with quotes automatically formatted if omitted.

func (Response[T]) WithHeader

func (r Response[T]) WithHeader(key, value string) Response[T]

WithHeader adds a response header.

func (Response[T]) WithHeaders

func (r Response[T]) WithHeaders(headers http.Header) Response[T]

WithHeaders merges all key-value pairs from headers into the response.

func (Response[T]) WithLastModified

func (r Response[T]) WithLastModified(t time.Time) Response[T]

WithLastModified sets the Last-Modified header formatted per RFC 7232.

func (Response[T]) WithStatus

func (r Response[T]) WithStatus(code int) Response[T]

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.

func (Response[T]) WriteToH1

func (r Response[T]) WriteToH1(res *h1engine.Response) error

WriteToH1 serializes the response directly into an h1.Response with zero net/http allocations.

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

func (r *Router) AllowedMethods(path string) []string

AllowedMethods returns all HTTP verbs registered for a given path across all routing trees.

func (*Router) FindTrailingSlash

func (r *Router) FindTrailingSlash(method, path string) (string, bool)

FindTrailingSlash tests if an alternate route exists with the opposite trailing slash.

func (*Router) HasPath

func (r *Router) HasPath(path string) bool

HasPath returns true if any HTTP method is registered for the specified path.

func (*Router) Match

func (r *Router) Match(method, path string, params *Params) (RawHandler, string, bool)

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.

func (*Router) Routes

func (r *Router) Routes() []RouteInfo

Routes returns an immutable slice of all registered RouteInfo metadata entries.

type SSEResponse

type SSEResponse struct {
	StreamFunc func(sse *SSESender) error
	Headers    http.Header
}

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.

func (SSEResponse) WriteToH1

func (r SSEResponse) WriteToH1(res *h1engine.Response) error

WriteToH1 configures SSE headers and binds SSESender for direct H1 delivery.

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

func NewSSESender(w io.Writer) *SSESender

NewSSESender creates an SSESender wrapping the destination network writer.

func (*SSESender) Send

func (s *SSESender) Send(data string) error

Send emits a simple data-only SSE message.

Example

_ = sse.Send("hello client")

func (*SSESender) SendComment

func (s *SSESender) SendComment(comment string) error

SendComment emits a comment line (heartbeat/keepalive ping).

func (*SSESender) SendEvent

func (s *SSESender) SendEvent(event, data string) error

SendEvent emits a named event with string payload.

Example

_ = sse.SendEvent("price_update", `{"symbol":"BTC","price":98000}`)

func (*SSESender) SendJSON

func (s *SSESender) SendJSON(event string, payload any) error

SendJSON emits a named event with an automatically serialized JSON payload.

Example

_ = sse.SendJSON("user_joined", User{ID: 42, Name: "Alice"})

func (*SSESender) SendRetry

func (s *SSESender) SendRetry(ms int) error

SendRetry advises the client reconnection backoff delay in milliseconds.

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 NewSecret

func NewSecret[T any](val T) Secret[T]

NewSecret creates a new protected Secret wrapping val.

func (Secret[T]) Expose

func (s Secret[T]) Expose() T

Expose returns the raw sensitive value. Synonym for [Value].

func (Secret[T]) Format

func (s Secret[T]) Format(f fmt.State, verb rune)

Format masks the secret during fmt.Sprintf printing.

func (Secret[T]) GoString

func (s Secret[T]) GoString() string

GoString masks the secret when formatted with %#v in debug prints.

func (Secret[T]) MarshalJSON

func (s Secret[T]) MarshalJSON() ([]byte, error)

MarshalJSON safely serializes the secret as a masked string to prevent leakage in API responses.

func (Secret[T]) String

func (s Secret[T]) String() string

String masks the secret when formatted with %s, %v, or fmt.Println.

func (*Secret[T]) UnmarshalJSON

func (s *Secret[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON deserializes the raw value into the protected container.

func (Secret[T]) Value

func (s Secret[T]) Value() T

Value returns the raw sensitive value for authorized business logic.

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 New

func New(opts ...Option) *Server

New creates a new, fully initialized Server instance configured with options.

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) Close

func (s *Server) Close() error

Close gracefully closes the server.

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

func (s *Server) DispatchH1(h1Req *h1engine.Request, h1Res *h1engine.Response) error

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) Listen

func (s *Server) Listen(addr string) error

Listen starts listening on the specified address.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe starts the native H1 zero-net/http server listening on the configured address.

func (*Server) ListenAndServeAutoTLS

func (s *Server) ListenAndServeAutoTLS(addr string, domains ...string) error

ListenAndServeAutoTLS starts the server with zero-config Let's Encrypt / ACME automatic TLS certificates (RFC 8555 & RFC 8737).

func (*Server) ListenAndServeQUIC

func (s *Server) ListenAndServeQUIC(addr, certFile, keyFile string) error

ListenAndServeQUIC starts the native HTTP/3 server over UDP using TLS.

func (*Server) ListenAndServeTLS

func (s *Server) ListenAndServeTLS(certFile, keyFile string) error

ListenAndServeTLS starts listening on s.addr with TLS using native H1 engine.

func (*Server) ListenAndServeUniversal

func (s *Server) ListenAndServeUniversal(addr, certFile, keyFile string) error

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

func (s *Server) MapErrors(errorsMap Errors) *Server

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

func (s *Server) MountModule(m Module) *Server

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

func (s *Server) PrintRoutes() string

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

func (s *Server) Routes() []RouteInfo

Routes returns an immutable snapshot list of all registered route patterns and methods in this server.

func (*Server) Serve

func (s *Server) Serve(ln net.Listener) error

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

func (s *Server) SetTrustedPlatform(platformHeader string)

SetTrustedPlatform configures the server to trust client IP addresses from specific cloud platform headers.

func (*Server) SetTrustedProxies

func (s *Server) SetTrustedProxies(proxies []string) error

SetTrustedProxies configures a list of trusted reverse proxy IP addresses or CIDR subnets.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down all server listeners (TCP H1/H2 and UDP QUIC H3).

func (*Server) Trace

func (s *Server) Trace(fn TraceHook) *Server

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

type ServerTimingEntry struct {
	Name        string
	Duration    time.Duration
	Description string
}

ServerTimingEntry records a single W3C Server-Timing entry.

type StreamResponse

type StreamResponse[T any] struct {
	Seq     iter.Seq[T]
	SSE     bool
	Event   string
	Headers http.Header
}

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.

func (StreamResponse[T]) WriteToH1

func (r StreamResponse[T]) WriteToH1(res *h1engine.Response) error

WriteToH1 satisfies DirectH1Responder for direct H1 delivery.

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.

func (StreamWriterResponse) WriteToH1

func (s StreamWriterResponse) WriteToH1(res *h1engine.Response) error

WriteToH1 streams data directly into the connection socket buffer via chunked transfer encoding.

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.

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.
sse
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.
tun
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.

Jump to

Keyboard shortcuts

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