Documentation
¶
Index ¶
- Constants
- func EnsureTrailingSlash(dir string) string
- func HealthCheckHandler(w http.ResponseWriter, r *http.Request)
- func PanicHandler(w http.ResponseWriter, r *http.Request)
- func RecoveryMiddleware(next http.Handler) http.HandlerFunc
- func RequestLoggerMiddleware(next http.Handler) http.HandlerFunc
- func ResponseTimeMiddleware(next http.Handler) http.HandlerFunc
- func TraceMiddleware(next http.Handler) http.HandlerFunc
- type DataFunc
- type Header
- type MiddlewareFunc
- type MiddlewareRegistry
- type MiddlewareStack
- type SSEMessage
- type Server
- func (srv *Server) AddMiddleware(route string, mw MiddlewareFunc)
- func (srv *Server) AddMiddlewareStack(route string, mw MiddlewareStack)
- func (srv *Server) Handle(pattern string, handlerFunc http.HandlerFunc)
- func (srv *Server) HandleFunc(pattern string, handler http.HandlerFunc)
- func (srv *Server) HandleFuncDynamic(pattern, tmplName string, dataFunc DataFunc) error
- func (srv *Server) HandleStatic(pattern string)
- func (srv *Server) HandleTemplate(pattern, t string, data interface{}) error
- func (srv *Server) Run() error
- func (srv *Server) Stop() error
- func (srv *Server) WithOutStack(stack MiddlewareStack) error
- type ServerOptionFunc
- func WithAddr(addr string) ServerOptionFunc
- func WithAuthTokenValidator(validator func(token string) (bool, error)) ServerOptionFunc
- func WithEncryptedClientHello(echKeys ...[]byte) ServerOptionFunc
- func WithFIPSMode() ServerOptionFunc
- func WithHealthServer() ServerOptionFunc
- func WithLogger(l *slog.Logger) ServerOptionFunc
- func WithLoglevel(level slog.Level) ServerOptionFunc
- func WithRateLimit(limit rateLimit, burst int) ServerOptionFunc
- func WithTLS(certFile, keyFile string) ServerOptionFunc
- func WithTemplateDir(dir string) ServerOptionFunc
- func WithTimeouts(readTimeout, writeTimeout, idleTimeout time.Duration) ServerOptionFunc
- type ServerOptions
Constants ¶
const ( // LevelDebug enables debug-level logging with detailed information LevelDebug = slog.LevelDebug // LevelInfo enables info-level logging for general information LevelInfo = slog.LevelInfo // LevelWarn enables warning-level logging for important but non-critical events LevelWarn = slog.LevelWarn // LevelError enables error-level logging for error conditions only LevelError = slog.LevelError )
Log level constants for server configuration. These wrap slog levels to provide a consistent API while hiding the logging implementation details.
const GlobalMiddlewareRoute = "*"
GlobalMiddlewareRoute is a special route identifier that applies middleware to all routes. Use this constant when registering middleware that should run for every request.
Variables ¶
This section is empty.
Functions ¶
func EnsureTrailingSlash ¶
EnsureTrailingSlash ensures that a directory path ends with a trailing slash. This utility function is used to normalize directory paths for consistent handling.
func HealthCheckHandler ¶
func HealthCheckHandler(w http.ResponseWriter, r *http.Request)
HealthCheckHandler returns a 204 No Content status code for basic health checks. This handler can be used as a simple liveness or readiness probe.
func PanicHandler ¶
func PanicHandler(w http.ResponseWriter, r *http.Request)
PanicHandler simulates a panic situation in a handler to test proper recovery middleware. This handler is intended for testing purposes only and should not be used in production.
func RecoveryMiddleware ¶
func RecoveryMiddleware(next http.Handler) http.HandlerFunc
RecoveryMiddleware returns a middleware function that recovers from panics in request handlers. Catches panics, logs the error, and returns a 500 Internal Server Error response.
func RequestLoggerMiddleware ¶
func RequestLoggerMiddleware(next http.Handler) http.HandlerFunc
RequestLoggerMiddleware returns a middleware function that logs detailed request information. Logs IP address, method, URL, trace ID, status code, and request duration. Use with caution as it may impact server performance.
func ResponseTimeMiddleware ¶
func ResponseTimeMiddleware(next http.Handler) http.HandlerFunc
ResponseTimeMiddleware returns a middleware function that logs only the request duration. This is a lighter alternative to RequestLoggerMiddleware when only timing information is needed.
func TraceMiddleware ¶
func TraceMiddleware(next http.Handler) http.HandlerFunc
TraceMiddleware returns a middleware function that adds trace IDs to requests. Generates unique trace IDs for request tracking and distributed tracing.
Types ¶
type DataFunc ¶
DataFunc is a function type that generates data for template rendering. It receives the current HTTP request and returns data to be passed to the template.
type Header ¶
type Header struct {
// contains filtered or unexported fields
}
Header represents an HTTP header key-value pair used in middleware configuration.
type MiddlewareFunc ¶
type MiddlewareFunc func(http.Handler) http.HandlerFunc
MiddlewareFunc is a function type that wraps an http.Handler and returns a new http.HandlerFunc. This is the standard pattern for HTTP middleware in Go.
func AuthMiddleware ¶
func AuthMiddleware(options *ServerOptions) MiddlewareFunc
AuthMiddleware returns a middleware function that validates bearer tokens in the Authorization header. Requires requests to include a valid Bearer token, otherwise returns 401 Unauthorized.
func ChaosMiddleware ¶
func ChaosMiddleware(options *ServerOptions) MiddlewareFunc
ChaosMiddleware returns a middleware handler that simulates random failures for chaos engineering. When chaos mode is enabled, can inject random latency, errors, throttling, and panics. Useful for testing application resilience and error handling.
func HeadersMiddleware ¶
func HeadersMiddleware(options *ServerOptions) MiddlewareFunc
HeadersMiddleware returns a middleware function that adds security headers to responses. Includes headers for XSS protection, content type sniffing prevention, HSTS, CSP, and CORS. Automatically handles CORS preflight requests.
func MetricsMiddleware ¶
func MetricsMiddleware(srv *Server) MiddlewareFunc
MetricsMiddleware returns a middleware function that collects request metrics. It tracks total request count and response times for performance monitoring.
func RateLimitMiddleware ¶
func RateLimitMiddleware(srv *Server) MiddlewareFunc
RateLimitMiddleware returns a middleware function that enforces rate limiting per client IP address. Uses token bucket algorithm with configurable rate limit and burst capacity. Returns 429 Too Many Requests when rate limit is exceeded. Optimized for Go 1.24's Swiss Tables map implementation.
type MiddlewareRegistry ¶
type MiddlewareRegistry struct {
// contains filtered or unexported fields
}
MiddlewareRegistry manages middleware stacks for different routes. It allows route-specific middleware configuration and supports exclusion of specific middleware.
func NewMiddlewareRegistry ¶
func NewMiddlewareRegistry(globalMiddleware MiddlewareStack) *MiddlewareRegistry
NewMiddlewareRegistry creates a new MiddlewareRegistry with optional global middleware. If globalMiddleware is provided, it will be applied to all routes by default.
func (*MiddlewareRegistry) Add ¶
func (mwr *MiddlewareRegistry) Add(route string, middleware MiddlewareStack)
Add registers a MiddlewareStack for a specific route in the registry. Use GlobalMiddlewareRoute ("*") to apply middleware to all routes.
func (*MiddlewareRegistry) Get ¶
func (mwr *MiddlewareRegistry) Get(route string) MiddlewareStack
Get retrieves the MiddlewareStack for a specific route. Returns an empty MiddlewareStack if no middleware is registered for the route.
func (*MiddlewareRegistry) RemoveStack ¶
func (mwr *MiddlewareRegistry) RemoveStack(route string)
RemoveStack removes all middleware for a specific route from the registry. Does nothing if no middleware is registered for the route.
type MiddlewareStack ¶
type MiddlewareStack []MiddlewareFunc
MiddlewareStack is a collection of middleware functions that can be applied to an http.Handler. Middleware in the stack is applied in order, with the first middleware being the outermost.
func DefaultMiddleware ¶
func DefaultMiddleware(server *Server) MiddlewareStack
DefaultMiddleware returns a predefined middleware stack with essential server functionality. Includes metrics collection, request logging, and panic recovery. This middleware is applied by default unless explicitly excluded.
func FileServer ¶
func FileServer(options *ServerOptions) MiddlewareStack
FileServer returns a middleware stack optimized for serving static files. Includes appropriate security headers for file serving.
func SecureAPI ¶
func SecureAPI(srv *Server) MiddlewareStack
SecureAPI returns a middleware stack configured for secure API endpoints. Includes authentication and rate limiting middleware.
func SecureWeb ¶
func SecureWeb(options *ServerOptions) MiddlewareStack
SecureWeb returns a middleware stack configured for secure web endpoints. Includes security headers middleware for web applications.
type SSEMessage ¶
type SSEMessage struct {
Event string `json:"event"` // Optional: Allows sending multiple event types
Data any `json:"data"` // The actual data payload
}
SSEMessage represents a Server-Sent Events message with an optional event type and data payload. It follows the SSE format with event and data fields that can be sent to clients.
func NewSSEMessage ¶
func NewSSEMessage(data any) *SSEMessage
NewSSEMessage creates a new SSE message with the given data and a default "message" event type. This is a convenience function for creating standard SSE messages.
func (*SSEMessage) String ¶
func (sse *SSEMessage) String() string
String formats the SSE message according to the Server-Sent Events specification. Returns a string in the format "event: <event>\ndata: <data>\n\n".
type Server ¶
type Server struct {
Options *ServerOptions
// contains filtered or unexported fields
}
Server represents an HTTP server that can handle requests and responses. It provides middleware support, health checks, template rendering, and various configuration options.
func NewServer ¶
func NewServer(opts ...ServerOptionFunc) (*Server, error)
NewServer creates a new instance of the Server with the given options. It initializes the server with default middleware and applies all provided ServerOptionFunc options. Returns an error if any of the options fail to apply.
func (*Server) AddMiddleware ¶
func (srv *Server) AddMiddleware(route string, mw MiddlewareFunc)
AddMiddleware adds a single middleware function to the specified route. Use "*" as the route to apply middleware globally to all routes.
func (*Server) AddMiddlewareStack ¶
func (srv *Server) AddMiddlewareStack(route string, mw MiddlewareStack)
AddMiddlewareStack adds a collection of middleware functions to the specified route. The middleware stack is applied in the order provided.
func (*Server) Handle ¶
func (srv *Server) Handle(pattern string, handlerFunc http.HandlerFunc)
Handle registers the handler function for the given pattern. This is a wrapper around http.ServeMux.Handle that integrates with the server's middleware system. Example usage:
srv.Handle("/static", http.FileServer(http.Dir("./static")))
func (*Server) HandleFunc ¶
func (srv *Server) HandleFunc(pattern string, handler http.HandlerFunc)
HandleFunc registers the handler function for the given pattern. This is a wrapper around http.ServeMux.HandleFunc that integrates with the server's middleware system. Example usage:
srv.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, world!")
})
func (*Server) HandleFuncDynamic ¶
HandleFuncDynamic registers a handler that renders templates with dynamic data. The dataFunc is called for each request to generate the data passed to the template. Returns an error if template parsing fails.
func (*Server) HandleStatic ¶
HandleStatic registers a handler for serving static files from the configured static directory. The pattern should typically end with a wildcard (e.g., "/static/"). Uses os.Root for secure file access when available (Go 1.24+).
func (*Server) HandleTemplate ¶
HandleTemplate registers a handler that renders a specific template with static data. Unlike HandleFuncDynamic, the data is provided once at registration time. Returns an error if template parsing fails.
func (*Server) Run ¶
Run starts the server and listens for incoming requests. It sets up TLS if enabled, starts the health server if configured, and handles graceful shutdown. Returns an error if the server fails to start or encounters an error during operation.
func (*Server) WithOutStack ¶
func (srv *Server) WithOutStack(stack MiddlewareStack) error
type ServerOptionFunc ¶
ServerOptionFunc is a function type used to configure Server instances. It follows the functional options pattern for flexible server configuration.
func WithAddr ¶
func WithAddr(addr string) ServerOptionFunc
WithAddr sets the address and port for the server to listen on. The address must be in the format "host:port" (e.g., ":8080", "localhost:3000").
func WithAuthTokenValidator ¶
func WithAuthTokenValidator(validator func(token string) (bool, error)) ServerOptionFunc
WithAuthTokenValidator sets the token validator for the server.
func WithEncryptedClientHello ¶
func WithEncryptedClientHello(echKeys ...[]byte) ServerOptionFunc
WithEncryptedClientHello enables Encrypted Client Hello (ECH) for enhanced privacy. ECH encrypts the SNI in TLS handshakes to prevent eavesdropping on the server name.
func WithFIPSMode ¶
func WithFIPSMode() ServerOptionFunc
WithFIPSMode enables FIPS 140-3 compliant mode for government and enterprise deployments. This restricts TLS cipher suites and curves to FIPS-approved algorithms only.
func WithHealthServer ¶
func WithHealthServer() ServerOptionFunc
WithHealthServer enables the health server on a separate port. The health server provides /healthz/, /readyz/, and /livez/ endpoints for monitoring.
func WithLogger ¶
func WithLogger(l *slog.Logger) ServerOptionFunc
WithLogger replaces the default logger with a custom slog.Logger instance. This allows for custom log formatting, output destinations, and log levels.
func WithLoglevel ¶
func WithLoglevel(level slog.Level) ServerOptionFunc
WithLoglevel sets the global log level for the server. Accepts slog.Level values (LevelDebug, LevelInfo, LevelWarn, LevelError).
func WithRateLimit ¶
func WithRateLimit(limit rateLimit, burst int) ServerOptionFunc
WithRateLimit configures rate limiting for the server. limit: maximum number of requests per second per client IP burst: maximum number of requests that can be made in a short burst
func WithTLS ¶
func WithTLS(certFile, keyFile string) ServerOptionFunc
WithTLS enables TLS on the server with the specified certificate and key files. Returns a ServerOptionFunc that configures TLS settings and validates file existence.
func WithTemplateDir ¶
func WithTemplateDir(dir string) ServerOptionFunc
WithTemplateDir sets the directory path where HTML templates are located. Templates in this directory can be used with HandleTemplate and HandleFuncDynamic methods.
func WithTimeouts ¶
func WithTimeouts(readTimeout, writeTimeout, idleTimeout time.Duration) ServerOptionFunc
WithTimeouts configures the HTTP server timeouts. readTimeout: maximum duration for reading the entire request writeTimeout: maximum duration before timing out writes of the response idleTimeout: maximum time to wait for the next request when keep-alives are enabled
type ServerOptions ¶
type ServerOptions struct {
Addr string `json:"addr,omitempty"`
EnableTLS bool `json:"tls,omitempty"`
TLSAddr string `json:"tls_addr,omitempty"`
TLSHealthAddr string `json:"tls_health_addr,omitempty"`
KeyFile string `json:"key_file,omitempty"`
CertFile string `json:"cert_file,omitempty"`
HealthAddr string `json:"health_addr,omitempty"`
RateLimit rateLimit `json:"rate_limit,omitempty"`
Burst int `json:"burst,omitempty"`
ReadTimeout time.Duration `json:"read_timeout,omitempty"`
WriteTimeout time.Duration `json:"write_timeout,omitempty"`
IdleTimeout time.Duration `json:"idle_timeout,omitempty"`
StaticDir string `json:"static_dir,omitempty"`
TemplateDir string `json:"template_dir,omitempty"`
RunHealthServer bool `json:"run_health_server,omitempty"`
ChaosMode bool `json:"chaos_mode,omitempty"`
ChaosMaxLatency time.Duration `json:"chaos_max_latency,omitempty"`
ChaosMinLatency time.Duration `json:"chaos_min_latency,omitempty"`
ChaosErrorRate float64 `json:"chaos_error_rate,omitempty"`
ChaosThrottleRate float64 `json:"chaos_throttle_rate,omitempty"`
ChaosPanicRate float64 `json:"chaos_panic_rate,omitempty"`
AuthTokenValidatorFunc func(token string) (bool, error)
FIPSMode bool `json:"fips_mode,omitempty"`
EnableECH bool `json:"enable_ech,omitempty"`
ECHKeys [][]byte `json:"-"` // ECH keys are sensitive, don't serialize
}
ServerOptions contains all configuration settings for the HTTP server. Options are loaded from environment variables, configuration files, and defaults in that priority order.
func NewServerOptions ¶
func NewServerOptions() *ServerOptions
NewServerOptions creates a new ServerOptions instance with values loaded in priority order: 1. Environment variables (highest priority) 2. Configuration file (options.json) 3. Default values (lowest priority) Returns a fully initialized ServerOptions struct ready for use.
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
auth
command
Example of how to use the auth package of Hyperserve
|
Example of how to use the auth package of Hyperserve |
|
chaos
command
|
|
|
enterprise
command
Enterprise example demonstrating FIPS 140-3 compliance and enhanced security features
|
Enterprise example demonstrating FIPS 140-3 compliance and enhanced security features |
|
htmx-dynamic
command
|
|
|
htmx-stream
command
|
|
|
go
module
|