hyperserve

package module
v0.9.0-beta Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2025 License: MIT Imports: 22 Imported by: 0

README ¶

HyperServe 🚀

A lightweight, high-performance HTTP server framework for Go with zero external dependencies (except golang.org/x/time/rate for rate limiting).

Go Version License

Features

🚀 Performance & Simplicity
  • Minimal overhead - Security middleware adds only 10-30% to baseline latency
  • Zero external dependencies - Pure Go implementation (only uses golang.org/x/time/rate)
  • Memory efficient - 10 allocations per request, ~1KB memory footprint
  • Flexible middleware system - Route-specific and global middleware chains
  • Built-in static file serving - Efficient static content delivery
  • Template engine integration - Dynamic HTML rendering with Go templates
  • Graceful shutdown - Proper cleanup and connection draining
🔒 Security & Reliability
  • TLS support - HTTPS with modern cipher suites, post-quantum ready (X25519MLKEM768)
  • FIPS 140-3 mode - Government-grade cryptographic compliance for enterprise deployments
  • Encrypted Client Hello - Enhanced privacy by encrypting SNI in TLS handshakes
  • Rate limiting - Optimized for Go 1.24's Swiss Tables with automatic cleanup
  • Timing attack protection - Constant-time authentication using crypto/subtle
  • Secure file serving - Uses os.Root for sandboxed directory access (Go 1.24)
  • Security headers - Modern 2024 security headers including CORS, CSP, HSTS, Cross-Origin policies, and Permissions-Policy
  • Health checks - Kubernetes-ready health endpoints (/healthz, /readyz, /livez)
  • Request tracing - Built-in trace ID generation for distributed systems
  • Panic recovery - Automatic recovery from handler panics
🎯 Developer Experience
  • Multiple configuration methods - Environment variables, JSON files, or code
  • Structured logging - Using Go's slog package
  • Metrics collection - Request count and latency tracking with automatic cleanup
  • Memory management - Built-in cleanup mechanisms prevent memory leaks from rate limiters
  • Server-Sent Events (SSE) - Real-time streaming support
  • Chaos engineering - Built-in chaos mode for resilience testing

Installation

go get github.com/osauer/hyperserve

Quick Start

package main

import (
    "fmt"
    "log"
    "net/http"
    
    "github.com/osauer/hyperserve"
)

func main() {
    // Create a new server
    srv, err := hyperserve.NewServer(
        hyperserve.WithAddr(":8080"),
        hyperserve.WithHealthServer(),
    )
    if err != nil {
        log.Fatal(err)
    }

    // Add middleware
    srv.AddMiddleware("*", hyperserve.MetricsMiddleware(srv))
    srv.AddMiddleware("/api", hyperserve.RateLimitMiddleware(srv))

    // Add routes
    srv.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Welcome to HyperServe!")
    })

    // Start the server
    if err := srv.Run(); err != nil {
        log.Fatal(err)
    }
}

Configuration

HyperServe supports three configuration methods (in order of precedence):

  1. Environment Variables (prefix: HS_)
  2. JSON Configuration File
  3. Default Values
Environment Variables
export HS_PORT=8080
export HS_RATE_LIMIT=100
export HS_BURST_LIMIT=200
export HS_LOG_LEVEL=info
export HS_CHAOS_MODE=false  # Default: false (production safe)
export HS_TLS_CERT_FILE=/path/to/cert.pem
export HS_TLS_KEY_FILE=/path/to/key.pem
JSON Configuration
{
    "port": 8080,
    "rateLimit": 100,
    "burstLimit": 200,
    "logLevel": "info",
    "enableTLS": true,
    "certFile": "/path/to/cert.pem",
    "keyFile": "/path/to/key.pem"
}
Programmatic Configuration
srv, err := hyperserve.NewServer(
    hyperserve.WithAddr(":8080"),
    hyperserve.WithTLS("cert.pem", "key.pem"),
    hyperserve.WithRateLimit(100, 200),
    hyperserve.WithTimeouts(30*time.Second, 30*time.Second, 120*time.Second),
    hyperserve.WithHealthServer(),
    hyperserve.WithFIPSMode(), // Enable FIPS 140-3 compliance
    hyperserve.WithEncryptedClientHello(echKeys...), // Enable ECH
)

Middleware

Built-in Middleware
// Logging and metrics
srv.AddMiddleware("*", hyperserve.RequestLoggerMiddleware)
srv.AddMiddleware("*", hyperserve.MetricsMiddleware(srv))

// Security
srv.AddMiddleware("/api", hyperserve.AuthMiddleware(srv.Options))
srv.AddMiddleware("*", hyperserve.HeadersMiddleware(srv.Options))

// Rate limiting
srv.AddMiddleware("/api", hyperserve.RateLimitMiddleware(srv))

// Recovery and tracing
srv.AddMiddleware("*", hyperserve.RecoveryMiddleware)
srv.AddMiddleware("*", hyperserve.TraceMiddleware)
Custom Middleware
func CustomMiddleware(next http.Handler) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // Before request
        log.Printf("Request: %s %s", r.Method, r.URL.Path)
        
        // Call next handler
        next.ServeHTTP(w, r)
        
        // After request
        log.Printf("Request completed")
    }
}

srv.AddMiddleware("/api", CustomMiddleware)

💡 Auth Integration: For authentication setup, see Authentication and Token Validation sections.

Middleware Stacks
// Pre-configured stacks
srv.AddMiddlewareStack("/api", hyperserve.SecureAPI(srv))
srv.AddMiddlewareStack("/", hyperserve.SecureWeb(srv.Options))
Rate Limiting Headers

The rate limiting middleware automatically adds informative headers to help clients understand their current rate limit status:

  • X-RateLimit-Limit: The maximum number of requests allowed per second
  • X-RateLimit-Remaining: The number of requests remaining in the current window
  • X-RateLimit-Reset: Unix timestamp when the rate limit resets
  • Retry-After: Seconds to wait before retrying when rate limited (429 responses)

Templates

// Configure template directory
srv.Options.TemplateDir = "./templates"

// Serve static template
srv.HandleTemplate("/about", "about.html", map[string]string{
    "title": "About Us",
    "content": "Welcome to our site",
})

// Dynamic template with data function
srv.HandleFuncDynamic("/user", "user.html", func(r *http.Request) interface{} {
    return map[string]interface{}{
        "username": r.URL.Query().Get("name"),
        "timestamp": time.Now().Format(time.RFC3339),
    }
})

Static Files

// Configure static directory
srv.Options.StaticDir = "./static"

// Serve static files
srv.HandleStatic("/static/")

Server-Sent Events (SSE)

srv.HandleFunc("/events", func(w http.ResponseWriter, r *http.Request) {
    // Set SSE headers
    w.Header().Set("Content-Type", "text/event-stream")
    w.Header().Set("Cache-Control", "no-cache")
    w.Header().Set("Connection", "keep-alive")

    // Send events
    for i := 0; i < 10; i++ {
        msg := hyperserve.NewSSEMessage(map[string]interface{}{
            "count": i,
            "time": time.Now().Format(time.RFC3339),
        })
        
        fmt.Fprintf(w, "event: %s\ndata: %s\n\n", msg.Event, msg.Data)
        w.(http.Flusher).Flush()
        
        time.Sleep(time.Second)
    }
})

Authentication

// Configure token validator
srv, _ := hyperserve.NewServer(
    hyperserve.WithAuthTokenValidator(func(token string) (bool, error) {
        // Implement your token validation logic
        // Example: validate JWT, check database, verify API key
        if token == "valid-secret-token" {
            return true, nil
        }
        return false, nil
    }),
)

// Apply auth middleware to protected routes
srv.AddMiddleware("/api", hyperserve.AuthMiddleware(srv.Options))

💡 See also: Token Validation for detailed implementation examples, Security Headers for additional protection, and Middleware Stacks for combining auth with other security features.

Token Validation

Token validation is a critical security component that determines whether incoming authentication tokens are legitimate. The validator function acts as the gatekeeper for protected routes, ensuring only authenticated requests can access secured endpoints. Proper token validation helps prevent unauthorized access and maintains application security.

The authentication middleware requires a token validator function to be configured. This function receives the bearer token and should return whether it's valid:

  • Return (true, nil) for valid tokens
  • Return (false, nil) for invalid tokens
  • Return (false, error) for validation errors

Example implementations:

// Simple API key validation
WithAuthTokenValidator(func(token string) (bool, error) {
    validTokens := map[string]bool{
        "api-key-123": true,
        "secret-token": true,
    }
    return validTokens[token], nil
})

// Comprehensive JWT validation with error handling
WithAuthTokenValidator(func(token string) (bool, error) {
    parsedToken, err := jwt.Parse(token, keyFunc)
    if err != nil {
        // Handle specific JWT errors
        if ve, ok := err.(*jwt.ValidationError); ok {
            switch {
            case ve.Errors&jwt.ValidationErrorMalformed != 0:
                return false, fmt.Errorf("malformed token")
            case ve.Errors&jwt.ValidationErrorExpired != 0:
                return false, fmt.Errorf("token expired")
            case ve.Errors&jwt.ValidationErrorNotValidYet != 0:
                return false, fmt.Errorf("token not valid yet")
            default:
                return false, fmt.Errorf("token validation failed: %v", err)
            }
        }
        return false, err
    }
    
    // Validate custom claims
    if claims, ok := parsedToken.Claims.(jwt.MapClaims); ok && parsedToken.Valid {
        // Check required claims
        if !claims.VerifyAudience("your-app", true) {
            return false, fmt.Errorf("invalid audience")
        }
        return true, nil
    }
    
    return false, fmt.Errorf("invalid token claims")
})

💡 Related: This pairs with Rate Limiting to prevent brute force attacks and Security Headers for defense in depth.

Go 1.24 Features

HyperServe leverages cutting-edge Go 1.24 features for enhanced performance and security:

FIPS 140-3 Compliance

Enable FIPS mode for government and regulated industry deployments:

srv, _ := hyperserve.NewServer(
    hyperserve.WithFIPSMode(),
)

This enables:

  • FIPS-approved cipher suites only
  • Restricted elliptic curves (P256, P384)
  • GOFIPS140 runtime mode
  • Compliance logging
Encrypted Client Hello (ECH)

Protect user privacy by encrypting the SNI:

echKeys := [][]byte{primaryKey, backupKey}
srv, _ := hyperserve.NewServer(
    hyperserve.WithEncryptedClientHello(echKeys...),
)
Post-Quantum Cryptography

HyperServe automatically enables X25519MLKEM768 key exchange when not in FIPS mode, providing protection against future quantum computer attacks.

Performance Optimizations
  • Swiss Tables: Rate limiting uses Go 1.24's faster map implementation
  • os.Root: Secure, sandboxed file serving prevents directory traversal
  • Timing Protection: Authentication uses crypto/subtle.WithDataIndependentTiming

See our benchmark results for detailed performance metrics.

Health Checks

When health server is enabled, the following endpoints are available on a separate port (default: :8081):

  • /healthz - Overall health status
  • /readyz - Readiness probe
  • /livez - Liveness probe
srv, _ := hyperserve.NewServer(
    hyperserve.WithHealthServer(),
)

Examples

Check out the examples directory for complete examples:

  • enterprise - Enterprise security with FIPS 140-3 and Go 1.24 features
  • htmx-dynamic - Dynamic content with HTMX 2.x
  • htmx-stream - Server-Sent Events with HTMX
  • chaos - Chaos engineering demonstration
  • auth - Authentication example

Testing

# Run all tests
go test ./...

# Run with race detection
go test -race ./...

# Run with coverage
go test -cover ./...

Chaos Mode

Enable chaos mode for testing application resilience:

export HS_CHAOS_MODE=true
export HS_CHAOS_ERROR_RATE=0.1
export HS_CHAOS_THROTTLE_RATE=0.05
export HS_CHAOS_MIN_LATENCY=100ms
export HS_CHAOS_MAX_LATENCY=500ms

Documentation

For comprehensive project documentation, see:

Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

License

HyperServe is released under the MIT License.

Documentation ¶

Index ¶

Constants ¶

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

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

func EnsureTrailingSlash(dir string) string

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 ¶

type DataFunc func(r *http.Request) interface{}

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 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 ¶

func (srv *Server) HandleFuncDynamic(pattern, tmplName string, dataFunc DataFunc) error

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 ¶

func (srv *Server) HandleStatic(pattern string)

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 ¶

func (srv *Server) HandleTemplate(pattern, t string, data interface{}) error

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 ¶

func (srv *Server) Run() error

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) Stop ¶

func (srv *Server) Stop() error

Stop gracefully stops the server with a default timeout of 10 seconds

func (*Server) WithOutStack ¶

func (srv *Server) WithOutStack(stack MiddlewareStack) error

type ServerOptionFunc ¶

type ServerOptionFunc func(srv *Server) error

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

Jump to

Keyboard shortcuts

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