Documentation
ΒΆ
Index ΒΆ
- Constants
- Variables
- func IsValidEmail(email string) bool
- func IsValidURL(url string) bool
- func IsValidUUID(uuid string) bool
- func JWTClaims(c *Context, contextKey ...string) jwt.MapClaims
- func NewValidator() *validator
- func Sanitize(input string) string
- func TrimInput(input string) string
- func ValidateRequired(input string) bool
- func ValidateStringLength(input string, minLen, maxLen int) bool
- type CORSConfig
- type CacheEntry
- type Config
- type Context
- func (c *Context) Accepted(data any) error
- func (c *Context) BadRequest(message string, details ...any) error
- func (c *Context) BindJSON(v any) error
- func (c *Context) Body() ([]byte, error)
- func (c *Context) Cookie(name string) string
- func (c *Context) Created(data any) error
- func (c *Context) Forbidden(message string) error
- func (c *Context) Get(key string) (any, bool)
- func (c *Context) HTML(code int, html string) error
- func (c *Context) Header(name string) string
- func (c *Context) InternalServerError(message string) error
- func (c *Context) JSON(code int, data any) error
- func (c *Context) Method() string
- func (c *Context) MustGet(key string) any
- func (c *Context) NoContent() error
- func (c *Context) NotFound(message string) error
- func (c *Context) OK(data any) error
- func (c *Context) Param(name string) string
- func (c *Context) Path() string
- func (c *Context) Query(name string) string
- func (c *Context) QueryDefault(name, defaultValue string) string
- func (c *Context) Redirect(code int, url string) error
- func (c *Context) Set(key string, value any)
- func (c *Context) SetContentType(contentType string)
- func (c *Context) SetCookie(cookie *http.Cookie)
- func (c *Context) SetHeader(key, value string)
- func (c *Context) StatusJSON(code int, data any) error
- func (c *Context) String(code int, text string) error
- func (c *Context) Unauthorized(message string) error
- type DocBuilder
- func (d *DocBuilder) Deprecated(b bool) *DocBuilder
- func (d *DocBuilder) Description(desc string) *DocBuilder
- func (d *DocBuilder) Meta(key string, value any) *DocBuilder
- func (d *DocBuilder) OperationID(id string) *DocBuilder
- func (d *DocBuilder) Param(name, in, description, schemaType string, required bool) *DocBuilder
- func (d *DocBuilder) ParamWithExample(name, in, description, schemaType string, required bool, example any) *DocBuilder
- func (d *DocBuilder) RequestBody(description string, example any) *DocBuilder
- func (d *DocBuilder) Response(statusCode int, description, contentType string, example any) *DocBuilder
- func (d *DocBuilder) Security(scheme string) *DocBuilder
- func (d *DocBuilder) Summary(s string) *DocBuilder
- func (d *DocBuilder) Tags(t ...string) *DocBuilder
- func (d *DocBuilder) ToMap() map[string]any
- type Encoder
- type Flux
- func (f *Flux) Any(path string, args ...any)
- func (f *Flux) DELETE(path string, args ...any)
- func (f *Flux) GET(path string, args ...any)
- func (f *Flux) Group(prefix string, args ...any) *Group
- func (f *Flux) HEAD(path string, args ...any)
- func (f *Flux) InitOpenAPI()
- func (f *Flux) Match(methods []string, path string, args ...any)
- func (f *Flux) OPTIONS(path string, args ...any)
- func (f *Flux) PATCH(path string, args ...any)
- func (f *Flux) POST(path string, args ...any)
- func (f *Flux) PUT(path string, args ...any)
- func (f *Flux) Pre(middleware ...MiddlewareFunc)
- func (f *Flux) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (f *Flux) Start(addr string, opts ...StartOption) error
- func (f *Flux) Stop(ctx context.Context) error
- func (f *Flux) Use(middleware ...MiddlewareFunc)
- type Group
- func (g *Group) Any(path string, args ...any)
- func (g *Group) DELETE(path string, args ...any)
- func (g *Group) GET(path string, args ...any)
- func (g *Group) Group(prefix string, args ...any) *Group
- func (g *Group) HEAD(path string, args ...any)
- func (g *Group) Match(methods []string, path string, args ...any)
- func (g *Group) OPTIONS(path string, args ...any)
- func (g *Group) PATCH(path string, args ...any)
- func (g *Group) POST(path string, args ...any)
- func (g *Group) PUT(path string, args ...any)
- func (g *Group) Use(middleware ...MiddlewareFunc)
- type HTTPError
- type HandlerFunc
- type Info
- type JWTConfig
- type Map
- type MiddlewareFunc
- func CORS(config CORSConfig) MiddlewareFunc
- func JWT(config JWTConfig) MiddlewareFunc
- func Logger() MiddlewareFunc
- func RateLimiter(config RateLimitConfig) MiddlewareFunc
- func Recover() MiddlewareFunc
- func RequestID() MiddlewareFunc
- func SecurityHeaders() MiddlewareFunc
- func Timeout(duration time.Duration) MiddlewareFunc
- type OpenAPISpec
- type Option
- type Param
- type Parameter
- type RateLimitConfig
- type Reloader
- type RequestBodyDoc
- type ResponseDoc
- type Route
- type RouteInfo
- type RouteNode
- type RouteOption
- type RouteOptions
- type Router
- type Schema
- type StartOption
- type StartupLogger
- type Validator
Constants ΒΆ
const ( GET = http.MethodGet POST = http.MethodPost PUT = http.MethodPut PATCH = http.MethodPatch DELETE = http.MethodDelete )
Variables ΒΆ
var (
// Version is the current stable version of the Flux framework.
Version = "1.4.1"
)
Functions ΒΆ
func IsValidEmail ΒΆ
IsValidEmail reports whether email is a properly formatted email address.
func IsValidURL ΒΆ
IsValidURL reports whether url begins with http:// or https:// and is syntactically plausible.
func IsValidUUID ΒΆ
IsValidUUID reports whether uuid is a canonical UUID v4 string (case-insensitive).
func JWTClaims ΒΆ
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 ΒΆ
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 ValidateRequired ΒΆ
ValidateRequired reports whether input is non-empty after trimming.
func ValidateStringLength ΒΆ
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 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) BadRequest ΒΆ
BadRequest returns a 400 Bad Request HTTPError.
func (*Context) BindJSON ΒΆ
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 ΒΆ
Body reads and returns the raw request body. The caller is responsible for closing the body.
func (*Context) InternalServerError ΒΆ
InternalServerError returns a 500 Internal Server Error HTTPError.
func (*Context) JSON ΒΆ
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) MustGet ΒΆ
MustGet retrieves a value from the context store, panicking if not found.
func (*Context) QueryDefault ΒΆ
QueryDefault returns the named query parameter, or defaultValue if absent.
func (*Context) SetContentType ΒΆ
SetContentType is a convenience wrapper for SetHeader("Content-Type", ...).
func (*Context) StatusJSON ΒΆ
StatusJSON is an alias for JSON (for explicit status-code readability).
func (*Context) Unauthorized ΒΆ
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 Flux ΒΆ
type Flux struct {
// contains filtered or unexported fields
}
Flux is the main framework instance.
func New ΒΆ
New returns a new Flux instance. It accepts optional configurators for future-proofing (e.g. custom encoders).
func (*Flux) Group ΒΆ
Group creates a route group with a shared prefix. Arguments can include MiddlewareFunc or string (for automatic documentation tags).
func (*Flux) InitOpenAPI ΒΆ
func (f *Flux) InitOpenAPI()
InitOpenAPI registers the /docs and /openapi.json endpoints.
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
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
Any registers a route for ALL standard HTTP methods within this group.
func (*Group) 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) Match ΒΆ added in v1.2.1
Match registers a route for a specific set of HTTP methods 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 ΒΆ
HTTPError represents a structured HTTP error that can be returned from any handler or middleware.
func NewHTTPError ΒΆ
NewHTTPError creates a new HTTPError. An optional details argument is included in the "details" field of the JSON response.
type HandlerFunc ΒΆ
HandlerFunc is the core request handler signature.
type Info ΒΆ added in v1.0.3
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.
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 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
WithEncoder allows providing a custom JSON encoder.
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 ΒΆ
RateLimitConfig holds rate limiting settings.
type Reloader ΒΆ added in v1.3.0
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
NewReloader creates a new Reloader for the given command and arguments.
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 (*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 ΒΆ
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.
Source Files
ΒΆ
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
|
|