flux

package module
v1.4.5 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2026 License: MIT Imports: 27 Imported by: 0

README ΒΆ

⚑️ Flux

Ultra-High Performance β€’ Zero Dependencies β€’ Auto-Documentation

Go Reference Go Report Card Build Status License Go Version

Flux is a next-generation web framework for Go, designed for developers who refuse to compromise on speed or security. Built on a trie-based zero-allocation router, it delivers bare-metal performance with a developer experience that feels like magic.


Features β€’ Quick Start β€’ Performance β€’ API Guide β€’ Deployment


πŸ’Ž Why Flux?

In an ecosystem of heavy frameworks, Flux stands out by being lightweight yet powerful.

Feature Flux Gin / Echo Standard Lib
Zero Dependencies βœ… ❌ βœ…
Zero-Allocation Router βœ… βœ… ❌
Built-in Middleware βœ… βœ… ❌
Auto-OpenAPI Docs βœ… ❌ ❌
Graceful Shutdown βœ… ❌ ❌
Type-Safe Validation βœ… βœ… ❌

"Flux is what happens when you combine the simplicity of Go's standard library with the power of a modern framework."


  • ⚑️ Elite Performance: Trie-based routing with Dynamic Parameter Pre-scaling for zero heap-allocations.
  • πŸ›‘ Zero Dependencies: No supply-chain bloat or security risks. Pure Go from the ground up.
  • πŸ“š Automatic Documentation: Native Scalar AI and OpenAPI 3.0 generation (at /docs).
  • πŸ” Security by Default: Built-in JWT, Rate Limiting, CORS, and Security Headers middleware.
  • πŸ”„ Hot Reloading: Native CLI tool for an instant development experience with zero setup.
  • πŸ§ͺ Multi-Core Scalability: Engineered for massive parallel throughput on modern ARM64 silicon.

🏁 Quick Start

Installation
go get github.com/ocuris/flux
The "Hello, Flux" Example
package main

import "github.com/ocuris/flux"

func main() {
    // 1. Initialize the app with metadata
    app := flux.New(flux.Config{
        Title:   "Payments API",
        Version: "1.0.0",
    })

    // 2. Global Middleware
    app.Use(flux.Recover())
    app.Use(flux.Logger())

    // 3. Define Routes
    app.GET("/welcome/:name", func(c *flux.Context) error {
        name := c.Param("name")
        return c.JSON(200, flux.Map{"message": "Hello, " + name + "!"})
    })

    // 4. Start Server (automatic graceful shutdown)
    app.Start(":8000")
}

Visit http://localhost:8000/docs to see your API come alive with auto-generated documentation.


πŸ’» Development Mode

Flux includes a native CLI (flx) to make development effortless. It supports "hot reloading" which automatically rebuilds and restarts your app when you save changes.

Installation (Homebrew)
brew tap ocuris/flux
brew install flx
Installation (Go)
go install github.com/ocuris/flux/cmd/flux@latest
Usage

Run your app with the --reload (or -r) flag to watch for changes:

flx --reload main.go

You can also enable it directly in your Config:

app := flux.New(flux.Config{
    Reload: true,
})

πŸ“Š Performance Benchmarks

Flux is engineered for ultra-high throughput. By eliminating mutex contention and minimizing the request-handling hot path, Flux delivers bare-metal performance that scales linearly with your hardware.

πŸ† Comprehensive Framework Comparison

All tests conducted on Apple M1 (8-core) with GOGC=100.

Metric (lower is better) ⚑️ Flux Gin Echo Fiber
8-Core Parallel Stress 3.9 ns πŸ₯‡ 5.2 ns 4.8 ns 2435 ns
Deep Route (7 segments) 22.0 ns πŸ₯‡ 26.7 ns 34.1 ns 4070 ns
Middleware (5 layers) 25.6 ns πŸ₯‡ 41.8 ns 109.0 ns 3881 ns
Large Scale (100 routes) 27.9 ns πŸ₯‡ 37.9 ns 36.9 ns N/A
JSON Response 1133 ns 1089 ns 1039 ns 7620 ns
Path Params (:id) 53.7 ns 33.2 ns 30.0 ns 4000 ns
πŸ“ˆ Scaling Analysis (1 to 8 Cores)

Flux features a lock-free routing engine, allowing it to scale almost perfectly as you add CPU cores.

Cores 1 2 4 8
Throughput (ns/op) 19.4 ns 10.1 ns 5.8 ns 3.9 ns
🧠 Why is Flux Faster?

For developers who care about the "How", Flux achieves these numbers through three core architectural decisions:

  1. Atomic Static Routing: Unlike frameworks that use a single shared Mutex or RWMutex for routing lookups, Flux uses method-specific atomic.Pointer maps. This enables $O(1)$ lock-free lookups for static routes, eliminating contention in high-concurrency environments.
  2. Zero-Allocation Context Pooling: Using a highly optimized sync.Pool with pre-allocated parameter slices (cap: 16), Flux ensures that standard requests never touch the heap.
  3. Low-Latency Hot Path: We removed defer from the core ServeHTTP loop and implemented early-exit middleware fast-paths. Every nanosecond saved in the engine is more CPU time for your business logic.

[!NOTE] Benchmarks were conducted using the provided benchmarks/Dockerfile on an Apple M1 Air (8-core). This ensures results are isolated and reproducible.


πŸ›  Core Concepts

πŸ›€ Routing & Groups

Manage complex API structures with ease using nested groups and local middleware.

v1 := app.Group("/api/v1")
v1.Use(authMiddleware)

v1.GET("/users", listUsers)
v1.POST("/users", createUser)

admin := v1.Group("/admin")
admin.Use(requireAdmin)
admin.GET("/stats", getStats)
πŸ“ Reading & Writing

Flux provides a high-level API for handling requests and responses without losing control.

func handler(c *flux.Context) error {
    id := c.Param("id")             // Path parameter
    var body MyRequest
    if err := c.BindJSON(&body); err != nil {
        return err                  // Automatic 400 with detail
    }
    return c.Created(body)          // 201 Created
}
🧱 Built-in Middleware

Everything you need for a production API is included:

  • flux.Recover(): Catch panics gracefully.
  • flux.JWT(): Professional HS256 authentication.
  • flux.RateLimiter(): Protection against abuse.
  • flux.CORS(): Secure cross-origin resource sharing.
  • flux.Timeout(): Bounded handler execution.

πŸ“– Automatic OpenAPI & Scalar AI

Flux automatically generates a complete OpenAPI 3.0 specification. It also includes the stunning Scalar AI documentation interface.

View Interactive Documentation details

Flux provides a powerful, interactive documentation UI via Scalar AI.

app.GET("/users/:id",
    flux.Doc("Get User", "Retrieve a user by their ID", "users").
        Param("id", "path", "User ID", "integer", true).
        Response(200, "User object", "application/json", nil),
    getUser,
)

πŸ›‘ Production Readiness

Graceful Shutdown

Flux handles SIGINT and SIGTERM automatically, draining in-flight requests before exiting.

Dockerized Deployment
FROM scratch
COPY --from=builder /server /server
EXPOSE 8000
ENTRYPOINT ["/server"]
Professional Makefile
make test        # Run unit tests
make bench       # Run the full elite benchmark suite
make vuln        # Scan for security vulnerabilities

🀝 Contributing & Community

Join us in building the fastest web framework for Go. Check out the CONTRIBUTING.md to get started.


πŸ“„ License

Flux is released under the MIT License. See LICENSE for details.

Built with ❀️ for the Go ecosystem by Ocuris.

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

View Source
const (
	GET    = http.MethodGet
	POST   = http.MethodPost
	PUT    = http.MethodPut
	PATCH  = http.MethodPatch
	DELETE = http.MethodDelete
)

Variables ΒΆ

View Source
var (
	// Version is the current stable version of the Flux framework.
	Version = "1.4.1"
)

Functions ΒΆ

func IsValidEmail ΒΆ

func IsValidEmail(email string) bool

IsValidEmail reports whether email is a properly formatted email address.

func IsValidURL ΒΆ

func IsValidURL(url string) bool

IsValidURL reports whether url begins with http:// or https:// and is syntactically plausible.

func IsValidUUID ΒΆ

func IsValidUUID(uuid string) bool

IsValidUUID reports whether uuid is a canonical UUID v4 string (case-insensitive).

func JWTClaims ΒΆ

func JWTClaims(c *Context, contextKey ...string) jwt.MapClaims

JWTClaims extracts jwt.MapClaims from a previously validated token stored in the context. It panics if the token is absent or has unexpected type.

claims := flux.JWTClaims(c)
email  := claims["email"].(string)

func NewValidator ΒΆ

func NewValidator() *validator

NewValidator returns the default validator instance.

func Sanitize ΒΆ

func Sanitize(input string) string

Sanitize HTML-escapes input to prevent XSS when the value is rendered in an HTML context. It converts <, >, &, ', and " to their HTML entities using the Go standard library β€” safer than a hand-rolled blocklist.

func TrimInput ΒΆ

func TrimInput(input string) string

TrimInput removes leading and trailing whitespace.

func ValidateRequired ΒΆ

func ValidateRequired(input string) bool

ValidateRequired reports whether input is non-empty after trimming.

func ValidateStringLength ΒΆ

func ValidateStringLength(input string, minLen, maxLen int) bool

ValidateStringLength reports whether the trimmed length of input falls within [minLen, maxLen] inclusive.

Types ΒΆ

type CORSConfig ΒΆ

type CORSConfig struct {
	AllowOrigins     []string
	AllowMethods     []string
	AllowHeaders     []string
	AllowCredentials bool
	MaxAge           int
}

CORSConfig is the configuration for the CORS middleware.

type CacheEntry ΒΆ

type CacheEntry struct {
	// contains filtered or unexported fields
}

CacheEntry is a cached result of a successful route match.

type Config ΒΆ

type Config struct {
	Title       string
	Version     string
	Description string
	Debug       bool
}

Config holds application configuration

type Context ΒΆ

type Context struct {
	Writer  http.ResponseWriter
	Request *http.Request
	// contains filtered or unexported fields
}

Context holds all the information for an HTTP request/response cycle.

func (*Context) Accepted ΒΆ

func (c *Context) Accepted(data any) error

Accepted sends a 202 Accepted JSON response.

func (*Context) BadRequest ΒΆ

func (c *Context) BadRequest(message string, details ...any) error

BadRequest returns a 400 Bad Request HTTPError.

func (*Context) BindJSON ΒΆ

func (c *Context) BindJSON(v any) error

BindJSON reads the request body, JSON-decodes it into v using the configured encoder, and runs validation. The body is always closed after this call.

func (*Context) Body ΒΆ

func (c *Context) Body() ([]byte, error)

Body reads and returns the raw request body. The caller is responsible for closing the body.

func (*Context) Cookie ΒΆ

func (c *Context) Cookie(name string) string

Cookie returns the value of the named cookie, or "" if not present.

func (*Context) Created ΒΆ

func (c *Context) Created(data any) error

Created sends a 201 Created JSON response.

func (*Context) Forbidden ΒΆ

func (c *Context) Forbidden(message string) error

Forbidden returns a 403 Forbidden HTTPError.

func (*Context) Get ΒΆ

func (c *Context) Get(key string) (any, bool)

Get retrieves a value from the per-request context store.

func (*Context) HTML ΒΆ

func (c *Context) HTML(code int, html string) error

HTML writes an HTML response with the given HTTP status code.

func (*Context) Header ΒΆ

func (c *Context) Header(name string) string

Header returns the value of the named request header.

func (*Context) InternalServerError ΒΆ

func (c *Context) InternalServerError(message string) error

InternalServerError returns a 500 Internal Server Error HTTPError.

func (*Context) JSON ΒΆ

func (c *Context) JSON(code int, data any) error

JSON marshals data to JSON and writes it with the given HTTP status code. After the first call, subsequent calls within the same request are no-ops to prevent double-write panics.

func (*Context) Method ΒΆ

func (c *Context) Method() string

Method returns the HTTP method of the current request.

func (*Context) MustGet ΒΆ

func (c *Context) MustGet(key string) any

MustGet retrieves a value from the context store, panicking if not found.

func (*Context) NoContent ΒΆ

func (c *Context) NoContent() error

NoContent sends a 204 No Content response.

func (*Context) NotFound ΒΆ

func (c *Context) NotFound(message string) error

NotFound returns a 404 Not Found HTTPError.

func (*Context) OK ΒΆ

func (c *Context) OK(data any) error

OK sends a 200 OK JSON response.

func (*Context) Param ΒΆ

func (c *Context) Param(name string) string

Param returns the value of the named path parameter, or "" if not present.

func (*Context) Path ΒΆ

func (c *Context) Path() string

Path returns the URL path of the current request.

func (*Context) Query ΒΆ

func (c *Context) Query(name string) string

Query returns the first value of the named URL query parameter.

func (*Context) QueryDefault ΒΆ

func (c *Context) QueryDefault(name, defaultValue string) string

QueryDefault returns the named query parameter, or defaultValue if absent.

func (*Context) Redirect ΒΆ

func (c *Context) Redirect(code int, url string) error

Redirect sends an HTTP redirect to url with the given status code.

func (*Context) Set ΒΆ

func (c *Context) Set(key string, value any)

Set stores an arbitrary value in the per-request context store.

func (*Context) SetContentType ΒΆ

func (c *Context) SetContentType(contentType string)

SetContentType is a convenience wrapper for SetHeader("Content-Type", ...).

func (*Context) SetCookie ΒΆ

func (c *Context) SetCookie(cookie *http.Cookie)

SetCookie adds a Set-Cookie header to the response.

func (*Context) SetHeader ΒΆ

func (c *Context) SetHeader(key, value string)

SetHeader sets a response header key/value pair.

func (*Context) StatusJSON ΒΆ

func (c *Context) StatusJSON(code int, data any) error

StatusJSON is an alias for JSON (for explicit status-code readability).

func (*Context) String ΒΆ

func (c *Context) String(code int, text string) error

String writes a plain-text response with the given HTTP status code.

func (*Context) Unauthorized ΒΆ

func (c *Context) Unauthorized(message string) error

Unauthorized returns a 401 Unauthorized HTTPError.

type DocBuilder ΒΆ

type DocBuilder struct {
	// contains filtered or unexported fields
}

DocBuilder manages OpenAPI metadata for a route.

func Doc ΒΆ

func Doc(summary, description string, tags ...string) *DocBuilder

Doc starts a new DocBuilder with positional arguments.

func (*DocBuilder) Deprecated ΒΆ

func (d *DocBuilder) Deprecated(b bool) *DocBuilder

Deprecated marks endpoint as deprecated

func (*DocBuilder) Description ΒΆ

func (d *DocBuilder) Description(desc string) *DocBuilder

Description sets the description

func (*DocBuilder) Meta ΒΆ

func (d *DocBuilder) Meta(key string, value any) *DocBuilder

Meta adds arbitrary metadata

func (*DocBuilder) OperationID ΒΆ

func (d *DocBuilder) OperationID(id string) *DocBuilder

OperationID sets OpenAPI operationId

func (*DocBuilder) Param ΒΆ

func (d *DocBuilder) Param(name, in, description, schemaType string, required bool) *DocBuilder

Param adds a parameter (path, query, header, cookie)

func (*DocBuilder) ParamWithExample ΒΆ

func (d *DocBuilder) ParamWithExample(name, in, description, schemaType string, required bool, example any) *DocBuilder

ParamWithExample adds a parameter with example value

func (*DocBuilder) RequestBody ΒΆ

func (d *DocBuilder) RequestBody(description string, example any) *DocBuilder

RequestBody sets the request body documentation

func (*DocBuilder) Response ΒΆ

func (d *DocBuilder) Response(statusCode int, description, contentType string, example any) *DocBuilder

Response adds response documentation

func (*DocBuilder) Security ΒΆ

func (d *DocBuilder) Security(scheme string) *DocBuilder

Security adds security requirement

func (*DocBuilder) Summary ΒΆ

func (d *DocBuilder) Summary(s string) *DocBuilder

Summary sets the summary

func (*DocBuilder) Tags ΒΆ

func (d *DocBuilder) Tags(t ...string) *DocBuilder

Tags sets tags for grouping

func (*DocBuilder) ToMap ΒΆ

func (d *DocBuilder) ToMap() map[string]any

ToMap converts to map for OpenAPI spec

type Encoder ΒΆ added in v1.0.3

type Encoder interface {
	Marshal(v any) ([]byte, error)
	Unmarshal(data []byte, v any) error
}

Encoder defines the JSON serialization interface.

type Flux ΒΆ

type Flux struct {
	// contains filtered or unexported fields
}

Flux is the main framework instance.

func New ΒΆ

func New(cfg Config, opts ...Option) *Flux

New returns a new Flux instance. It accepts optional configurators for future-proofing (e.g. custom encoders).

func (*Flux) Any ΒΆ added in v1.2.1

func (f *Flux) Any(path string, args ...any)

Any registers a route for ALL standard HTTP methods.

func (*Flux) DELETE ΒΆ

func (f *Flux) DELETE(path string, args ...any)

DELETE registers a handler for HTTP DELETE requests.

func (*Flux) GET ΒΆ

func (f *Flux) GET(path string, args ...any)

GET registers a handler for HTTP GET requests.

func (*Flux) Group ΒΆ

func (f *Flux) Group(prefix string, args ...any) *Group

Group creates a route group with a shared prefix. Arguments can include MiddlewareFunc or string (for automatic documentation tags).

func (*Flux) HEAD ΒΆ

func (f *Flux) HEAD(path string, args ...any)

HEAD registers a handler for HTTP HEAD requests.

func (*Flux) InitOpenAPI ΒΆ

func (f *Flux) InitOpenAPI()

InitOpenAPI registers the /docs and /openapi.json endpoints.

func (*Flux) Match ΒΆ added in v1.2.1

func (f *Flux) Match(methods []string, path string, args ...any)

Match registers a route for a specific set of HTTP methods.

func (*Flux) OPTIONS ΒΆ

func (f *Flux) OPTIONS(path string, args ...any)

OPTIONS registers a handler for HTTP OPTIONS requests.

func (*Flux) PATCH ΒΆ

func (f *Flux) PATCH(path string, args ...any)

PATCH registers a handler for HTTP PATCH requests.

func (*Flux) POST ΒΆ

func (f *Flux) POST(path string, args ...any)

POST registers a handler for HTTP POST requests.

func (*Flux) PUT ΒΆ

func (f *Flux) PUT(path string, args ...any)

PUT registers a handler for HTTP PUT requests.

func (*Flux) Pre ΒΆ

func (f *Flux) Pre(middleware ...MiddlewareFunc)

Pre registers pre-routing middleware. Unlike Use(), Pre() middleware runs before the route is matched on every request, making it suitable for tasks like request rewriting, canonical path normalisation, or early abort.

func (*Flux) ServeHTTP ΒΆ

func (f *Flux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler. It is the core entry point for every request. It features built-in panic recovery and path sanitisation to ensure stability.

func (*Flux) Start ΒΆ

func (f *Flux) Start(addr string, opts ...StartOption) error

Start registers the OpenAPI documentation endpoints, launches the HTTP server, and blocks until SIGINT or SIGTERM is received, then performs a graceful 30-second shutdown.

func (*Flux) Stop ΒΆ added in v1.0.2

func (f *Flux) Stop(ctx context.Context) error

Stop signals the server to begin its graceful shutdown sequence using the provided context for timeout/deadline control.

func (*Flux) Use ΒΆ

func (f *Flux) Use(middleware ...MiddlewareFunc)

Use appends global middleware to the application. Middleware must be registered before routes.

type Group ΒΆ

type Group struct {
	// contains filtered or unexported fields
}

Group facilitates route prefixing, shared middleware, and metadata inheritance.

func (*Group) Any ΒΆ added in v1.2.1

func (g *Group) Any(path string, args ...any)

Any registers a route for ALL standard HTTP methods within this group.

func (*Group) DELETE ΒΆ

func (g *Group) DELETE(path string, args ...any)

DELETE registers a DELETE handler within this group.

func (*Group) GET ΒΆ

func (g *Group) GET(path string, args ...any)

GET registers a GET handler within this group.

func (*Group) Group ΒΆ

func (g *Group) Group(prefix string, args ...any) *Group

Group creates a nested group with an additional prefix relative to this group. The parent group's tags and middleware are inherited.

func (*Group) HEAD ΒΆ

func (g *Group) HEAD(path string, args ...any)

HEAD registers a HEAD handler within this group.

func (*Group) Match ΒΆ added in v1.2.1

func (g *Group) Match(methods []string, path string, args ...any)

Match registers a route for a specific set of HTTP methods within this group.

func (*Group) OPTIONS ΒΆ

func (g *Group) OPTIONS(path string, args ...any)

OPTIONS registers an OPTIONS handler within this group.

func (*Group) PATCH ΒΆ

func (g *Group) PATCH(path string, args ...any)

PATCH registers a PATCH handler within this group.

func (*Group) POST ΒΆ

func (g *Group) POST(path string, args ...any)

POST registers a POST handler within this group.

func (*Group) PUT ΒΆ

func (g *Group) PUT(path string, args ...any)

PUT registers a PUT handler within this group.

func (*Group) Use ΒΆ

func (g *Group) Use(middleware ...MiddlewareFunc)

Use appends group-scoped middleware. These run after global middleware and before the route handler.

type HTTPError ΒΆ

type HTTPError struct {
	Code    int
	Message string
	Details any
}

HTTPError represents a structured HTTP error that can be returned from any handler or middleware.

func NewHTTPError ΒΆ

func NewHTTPError(code int, message string, details ...any) *HTTPError

NewHTTPError creates a new HTTPError. An optional details argument is included in the "details" field of the JSON response.

func (*HTTPError) Error ΒΆ

func (e *HTTPError) Error() string

type HandlerFunc ΒΆ

type HandlerFunc func(*Context) error

HandlerFunc is the core request handler signature.

type Info ΒΆ added in v1.0.3

type Info struct {
	Summary     string
	Description string
	Tags        []string
}

func (Info) Param ΒΆ added in v1.0.3

func (i Info) Param(name, in, description, schemaType string, required bool) *DocBuilder

Param allows chaining parameters directly on an Info struct.

func (Info) RequestBody ΒΆ added in v1.1.0

func (i Info) RequestBody(description string, schema any) *DocBuilder

RequestBody allows chaining a request body schema directly on an Info struct.

func (Info) Response ΒΆ added in v1.0.3

func (i Info) Response(code int, description, contentType string, schema any) *DocBuilder

Response allows chaining responses directly on an Info struct.

type JWTConfig ΒΆ

type JWTConfig struct {
	// SecretKey is the HMAC signing secret used to validate tokens.
	SecretKey []byte

	// Skipper is an optional function; return true to bypass JWT validation
	// for a given request (e.g. public health-check endpoints).
	Skipper func(c *Context) bool

	// ContextKey is the key under which the parsed *jwt.Token is stored in
	// the request context. Defaults to "user".
	ContextKey string

	// TokenLookup defines how to extract the raw token string.
	// Format: "source:name"  where source is one of: header, query, cookie.
	// Default: "header:Authorization"  (supports "Bearer <token>" prefix)
	TokenLookup string
}

JWTConfig holds the configuration for the JWT authentication middleware.

type Map ΒΆ

type Map map[string]any

Map is a shortcut for map[string]any, used primarily for JSON payloads.

type MiddlewareFunc ΒΆ

type MiddlewareFunc func(HandlerFunc) HandlerFunc

MiddlewareFunc wraps a HandlerFunc with additional behaviour.

func CORS ΒΆ

func CORS(config CORSConfig) MiddlewareFunc

CORS adds Cross-Origin Resource Sharing headers and handles OPTIONS preflight.

func JWT ΒΆ

func JWT(config JWTConfig) MiddlewareFunc

JWT returns middleware that validates HMAC-signed JWT tokens and stores the parsed token in the context under config.ContextKey.

app.Use(flux.JWT(flux.JWTConfig{SecretKey: []byte("my-secret")}))

Access the token inside a handler:

token  := c.MustGet("user").(*jwt.Token)
claims := token.Claims.(jwt.MapClaims)

func Logger ΒΆ

func Logger() MiddlewareFunc

Logger logs every request: method, path, status code, and elapsed time. It reads c.statusCode after the full handler chain (including error handling) has completed, so it always reflects the actual HTTP status sent to the client.

func RateLimiter ΒΆ

func RateLimiter(config RateLimitConfig) MiddlewareFunc

RateLimiter enforces a per-IP sliding-window request limit using a sharded in-memory store to reduce mutex contention.

func Recover ΒΆ

func Recover() MiddlewareFunc

Recover catches any panic in downstream handlers, logs the panic value and full stack trace to stderr, and returns a 500 Internal Server Error.

func RequestID ΒΆ

func RequestID() MiddlewareFunc

RequestID ensures every request has a unique X-Request-ID header. It propagates any ID supplied by the client; otherwise a cryptographically random 32-hex-character ID is generated.

func SecurityHeaders ΒΆ

func SecurityHeaders() MiddlewareFunc

SecurityHeaders adds common defensive HTTP headers to every response.

func Timeout ΒΆ

func Timeout(duration time.Duration) MiddlewareFunc

Timeout sets a deadline on the request's context.Context. Any downstream handler or I/O operation that respects ctx.Done() (e.g. database calls, outbound HTTP requests) will be cancelled when the timeout elapses.

Unlike the previous goroutine-based implementation, this approach carries no risk of a data race or goroutine leak. The server-level WriteTimeout provides a hard cap for handlers that do not use the context.

type OpenAPISpec ΒΆ

type OpenAPISpec struct {
	// contains filtered or unexported fields
}

OpenAPISpec represents the OpenAPI specification

type Option ΒΆ added in v1.0.3

type Option func(*Flux)

Option is a functional configuration for the Flux app.

func WithEncoder ΒΆ added in v1.0.3

func WithEncoder(e Encoder) Option

WithEncoder allows providing a custom JSON encoder.

type Param ΒΆ

type Param struct {
	Key   string
	Value string
}

Param represents a URL path parameter (e.g. :id β†’ {Key:"id", Value:"123"}).

type Parameter ΒΆ

type Parameter struct {
	Name        string  `json:"name"`
	In          string  `json:"in"` // path, query, header, cookie
	Description string  `json:"description"`
	SchemaType  string  `json:"type"` // string, number, integer, boolean, array, object
	Required    bool    `json:"required"`
	Schema      *Schema `json:"schema,omitempty"`
	Example     any     `json:"example,omitempty"`
}

Parameter describes a route parameter (path, query, header, etc.)

type RateLimitConfig ΒΆ

type RateLimitConfig struct {
	MaxRequests int
	Window      time.Duration
}

RateLimitConfig holds rate limiting settings.

type Reloader ΒΆ added in v1.3.0

type Reloader struct {
	Args     []string
	Interval time.Duration
}

Reloader manages a hot-reload lifecycle for a command. It monitors the filesystem for changes to .go files and restarts a child process.

func NewReloader ΒΆ added in v1.3.0

func NewReloader(args ...string) *Reloader

NewReloader creates a new Reloader for the given command and arguments.

func (*Reloader) Run ΒΆ added in v1.3.0

func (r *Reloader) Run() error

Run starts the file watcher and the managed subprocess. It blocks until a termination signal (SIGINT, SIGTERM) is received.

type RequestBodyDoc ΒΆ

type RequestBodyDoc struct {
	Description string  `json:"description"`
	Schema      *Schema `json:"schema"`
	Required    bool    `json:"required"`
	Example     any     `json:"example"`
}

RequestBodyDoc describes request body

type ResponseDoc ΒΆ

type ResponseDoc struct {
	Description string  `json:"description"`
	ContentType string  `json:"content_type"`
	Schema      *Schema `json:"schema"`
	Example     any     `json:"example"`
}

ResponseDoc describes a response

type Route ΒΆ

type Route struct {
	Method string `json:"method"`
	Path   string `json:"path"`
	Name   string `json:"name"`
}

Route represents a registered route (used by OpenAPI generation).

type RouteInfo ΒΆ

type RouteInfo struct {
	Method string
	Path   string
	Doc    *DocBuilder
}

RouteInfo holds metadata for a single registered route (used by OpenAPI).

type RouteNode ΒΆ

type RouteNode struct {
	// contains filtered or unexported fields
}

RouteNode is one node in the routing trie.

type RouteOption ΒΆ

type RouteOption func(*RouteOptions)

RouteOption is a function that configures RouteOptions

type RouteOptions ΒΆ

type RouteOptions struct {
	Summary     string
	Description string
	Tags        []string
	RequestBody any
	Responses   map[int]any
}

RouteOptions holds route metadata for OpenAPI

type Router ΒΆ

type Router struct {
	// contains filtered or unexported fields
}

Router implements a trie-based HTTP router with an atomic static-route lookup.

func NewRouter ΒΆ

func NewRouter() *Router

NewRouter creates a new empty Router.

func (*Router) Add ΒΆ

func (r *Router) Add(method, path string, handler HandlerFunc)

Add registers method+path in the trie with the given (already middleware-composed) handler.

Segment types:

  • "segment" β†’ static match (fastest)
  • ":name" β†’ named parameter (captures one path segment)
  • "*" β†’ wildcard catch-all (captures the rest of the path as param "*")

func (*Router) Match ΒΆ

func (r *Router) Match(method, path string, params *[]Param) (HandlerFunc, bool)

Match finds the handler for method+path.

Returns:

  • handler: the matched HandlerFunc (nil if not found)
  • params: path parameters extracted from the URL
  • methodNotAllowed: true when the path matched but not for this method (β†’ 405)

type Schema ΒΆ

type Schema struct {
	Type        string             `json:"type,omitempty"`
	Format      string             `json:"format,omitempty"`
	Description string             `json:"description,omitempty"`
	Properties  map[string]*Schema `json:"properties,omitempty"`
	Items       *Schema            `json:"items,omitempty"`
	Example     any                `json:"example,omitempty"`
	Default     any                `json:"default,omitempty"`
	Enum        []any              `json:"enum,omitempty"`
	MinLength   *int               `json:"minLength,omitempty"`
	MaxLength   *int               `json:"maxLength,omitempty"`
	Pattern     string             `json:"pattern,omitempty"`
	Minimum     *float64           `json:"minimum,omitempty"`
	Maximum     *float64           `json:"maximum,omitempty"`
	Required    []string           `json:"required,omitempty"`
}

Schema describes OpenAPI schema

type StartOption ΒΆ

type StartOption func(*http.Server)

StartOption is a functional option applied to the underlying *http.Server.

type StartupLogger ΒΆ

type StartupLogger struct {
	// contains filtered or unexported fields
}

StartupLogger prints the startup banner and server URLs when the app boots.

func NewStartupLogger ΒΆ

func NewStartupLogger(config Config) *StartupLogger

NewStartupLogger creates a StartupLogger with the given Config.

func (*StartupLogger) AddRoute ΒΆ

func (l *StartupLogger) AddRoute(method, path string, doc *DocBuilder)

AddRoute records a registered route for display at startup.

func (*StartupLogger) PrintStartup ΒΆ

func (l *StartupLogger) PrintStartup(addr string)

PrintStartup prints the startup banner to stdout. If the process is a hot-reload child that has been restarted, it prints a concise message.

type Validator ΒΆ

type Validator interface {
	Validate(i any) error
}

Validator is the interface for struct validation.

Directories ΒΆ

Path Synopsis
cmd
flux command
example
advanced command
auth command
basic command
bench-noop command
deep-test command
documented command
grand_tour command
high-throughput command
method-test command
validation command

Jump to

Keyboard shortcuts

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