Documentation
¶
Overview ¶
Package server: MCP (Model Context Protocol) glue.
The MCP protocol itself lives in github.com/osauer/hyperserve/pkg/mcp. This file wires *Server up to *mcp.Handler: server options that flip MCP modes, the discovery endpoint registration, and the thin Register* helpers that delegate into the handler.
Package server provides built-in middleware for common HTTP server functionality.
The middleware package includes:
- Request logging with structured output
- Panic recovery to prevent server crashes
- Request metrics collection
- Authentication (Basic, Bearer token, custom)
- Rate limiting per IP address
- Security headers (HSTS, CSP, etc.)
- Request/Response timing
Middleware can be applied globally or to specific routes:
// Global middleware
srv.AddMiddleware("*", server.RequestLoggerMiddleware)
// Route-specific middleware
srv.AddMiddleware("/api", server.AuthMiddleware(srv.Options))
// Combine multiple middleware
srv.AddMiddlewareGroup("/admin",
server.AuthMiddleware(srv.Options),
server.RateLimitMiddleware(srv),
)
Package hyperserve provides configuration options for the HTTP server.
Configuration follows a hierarchical priority:
- Function parameters (highest priority)
- Environment variables
- Configuration file (options.json)
- Default values (lowest priority)
Environment Variables:
- SERVER_ADDR: Main server address (default ":8080")
- HEALTH_ADDR: Health check server address (default ":8081")
- HS_HARDENED_MODE: Enable security headers (default "false")
- HS_MCP_ENABLED: Enable Model Context Protocol (default "false")
- HS_MCP_ENDPOINT: MCP endpoint path (default "/mcp")
- HS_MCP_DEV: Enable MCP developer tools (default "false")
- HS_MCP_OBSERVABILITY: Enable MCP observability resources (default "false")
- HS_MCP_TRANSPORT: MCP transport type: "http" or "stdio" (default "http")
- HS_CSP_WEB_WORKER_SUPPORT: Enable Web Worker CSP headers (default "false")
- HS_LOG_LEVEL: Set log level (DEBUG, INFO, WARN, ERROR) (default "INFO")
- HS_DEBUG: Enable debug mode and debug logging (default "false")
- HS_SUPPRESS_BANNER: Suppress the HyperServe ASCII banner at startup (default "false")
Example configuration file (options.json):
{
"addr": ":3000",
"tls": true,
"cert_file": "server.crt",
"key_file": "server.key",
"run_health_server": true,
"hardened_mode": true,
"debug_mode": false,
"log_level": "INFO"
}
Package server provides a lightweight, high-performance HTTP server framework with minimal external dependencies (golang.org/x/time/rate for rate limiting only).
Key Features:
- Zero configuration with sensible defaults
- Built-in middleware for logging, recovery, and metrics
- Graceful shutdown handling with application hooks
- Health check endpoints for Kubernetes
- Model Context Protocol (MCP) support for AI assistants
- WebSocket support for real-time communication (standard library only)
- TLS/HTTPS support with automatic certificate management
- Rate limiting and authentication
- Template rendering support
- Server-Sent Events (SSE) support
Basic Usage:
srv, err := server.NewServer()
if err != nil {
log.Fatal(err)
}
srv.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, World!")
})
srv.Run() // Blocks until shutdown signal
With Options:
srv, err := server.NewServer(
server.WithAddr(":8080"),
server.WithHealthServer(),
server.WithTLS("cert.pem", "key.pem"),
server.WithMCPSupport("MyApp", "1.0.0"),
)
Graceful Shutdown with Hooks:
srv, err := server.NewServer(
server.WithAddr(":8080"),
server.WithOnShutdown(func(ctx context.Context) error {
log.Println("Stopping background workers...")
// Stop your application's goroutines, close connections, etc.
return nil
}),
)
WebSocket Support (import websocket "github.com/osauer/hyperserve/pkg/websocket"):
upgrader := websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true // Configure based on your needs
},
}
srv.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("WebSocket upgrade error: %v", err)
return
}
defer conn.Close()
// Handle WebSocket messages
for {
messageType, p, err := conn.ReadMessage()
if err != nil {
break
}
// Echo message back
conn.WriteMessage(messageType, p)
}
})
Index ¶
- Constants
- Variables
- func DefaultLogger() *slog.Logger
- func EnsureTrailingSlash(dir string) string
- func GetVersionInfo() string
- func HealthCheckHandler(w http.ResponseWriter, r *http.Request)
- func MCPDev() mcp.TransportConfig
- func MCPObservability() mcp.TransportConfig
- 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 SetBuiltinPresetHooks(tools, standardResources, observability, developer func(*Server))
- func SetDefaultLogger(l *slog.Logger)
- func TraceMiddleware(next http.Handler) http.HandlerFunc
- type AuthTokenInjector
- type CORSOptions
- type DataFunc
- type Header
- type InterceptableRequest
- type InterceptableResponse
- type Interceptor
- type InterceptorChain
- type InterceptorResponse
- type MiddlewareFunc
- type MiddlewareRegistry
- type MiddlewareStack
- type RateLimit
- type RateLimitInterceptor
- func (rli *RateLimitInterceptor) InterceptRequest(ctx context.Context, req *InterceptableRequest) (*InterceptorResponse, error)
- func (rli *RateLimitInterceptor) InterceptResponse(ctx context.Context, req *InterceptableRequest, resp *InterceptableResponse) error
- func (rli *RateLimitInterceptor) Name() string
- type RateLimiter
- type RequestLogger
- type ResponseTransformer
- func (rt *ResponseTransformer) InterceptRequest(ctx context.Context, req *InterceptableRequest) (*InterceptorResponse, error)
- func (rt *ResponseTransformer) InterceptResponse(ctx context.Context, req *InterceptableRequest, resp *InterceptableResponse) error
- func (rt *ResponseTransformer) Name() string
- type SSEMessage
- type Server
- func (srv *Server) AddMetrics(deltaRequests uint64, deltaResponseTime int64)
- func (srv *Server) AddMiddleware(route string, mw MiddlewareFunc)
- func (srv *Server) AddMiddlewareStack(route string, mw MiddlewareStack)
- func (srv *Server) ClientLimiterCount() int
- func (srv *Server) CompleteDeferredInit(ctx context.Context, err error) error
- 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 any) error
- func (srv *Server) Handler() http.Handler
- func (srv *Server) IsReady() bool
- func (srv *Server) IsRunning() bool
- func (srv *Server) MCPEnabled() bool
- func (srv *Server) MCPHandler() *mcp.Handler
- func (srv *Server) MiddlewareRoutes() map[string]MiddlewareStack
- func (srv *Server) Mux() *http.ServeMux
- func (srv *Server) RegisterMCPExtension(ext mcp.Extension) error
- func (srv *Server) RegisterMCPNamespace(name string, configs ...mcp.NamespaceConfig) error
- func (srv *Server) RegisterMCPResource(resource mcp.Resource) error
- func (srv *Server) RegisterMCPResourceInNamespace(resource mcp.Resource, namespace string) error
- func (srv *Server) RegisterMCPTool(tool mcp.Tool) error
- func (srv *Server) RegisterMCPToolInNamespace(tool mcp.Tool, namespace string) error
- func (srv *Server) Run() error
- func (srv *Server) ServerStart() time.Time
- func (srv *Server) SetMetrics(totalRequests uint64, totalResponseTime int64)
- func (srv *Server) Stop() error
- func (srv *Server) TotalRequests() uint64
- func (srv *Server) TotalResponseTime() int64
- func (srv *Server) WebSocketUpgrader() *websocket.Upgrader
- func (srv *Server) WithOutStack(stack MiddlewareStack) error
- type ServerOptionFunc
- func WithAddr(addr string) ServerOptionFunc
- func WithAuthTokenValidator(validator func(token string) (bool, error)) ServerOptionFunc
- func WithBannerColor(enabled bool) ServerOptionFunc
- func WithCORS(opts *CORSOptions) ServerOptionFunc
- func WithCSPWebWorkerSupport() ServerOptionFunc
- func WithDebugMode() ServerOptionFunc
- func WithDeferredInit(fn func(context.Context, *Server) error) ServerOptionFunc
- func WithDeferredInitStopOnFailure(stop bool) ServerOptionFunc
- func WithFIPSMode() ServerOptionFunc
- func WithHardenedMode() ServerOptionFunc
- func WithHealthServer() ServerOptionFunc
- func WithIdleTimeout(timeout time.Duration) ServerOptionFunc
- func WithLogger(l *slog.Logger) ServerOptionFunc
- func WithLoglevel(level slog.Level) ServerOptionFunc
- func WithMCPBuiltinResources(enabled bool) ServerOptionFunc
- func WithMCPBuiltinTools(enabled bool) ServerOptionFunc
- func WithMCPDiscoveryFilter(filter func(toolName string, r *http.Request) bool) ServerOptionFunc
- func WithMCPDiscoveryPolicy(policy mcp.DiscoveryPolicy) ServerOptionFunc
- func WithMCPEndpoint(endpoint string) ServerOptionFunc
- func WithMCPFileToolRoot(rootDir string) ServerOptionFunc
- func WithMCPNamespace(name string, configs ...mcp.NamespaceConfig) ServerOptionFunc
- func WithMCPSupport(name, version string, configs ...mcp.TransportConfig) ServerOptionFunc
- func WithOnReady(hook func(context.Context, *Server) error) ServerOptionFunc
- func WithOnShutdown(hook func(context.Context) error) ServerOptionFunc
- func WithRateLimit(limit RateLimit, burst int) ServerOptionFunc
- func WithReadHeaderTimeout(timeout time.Duration) ServerOptionFunc
- func WithReadTimeout(timeout time.Duration) ServerOptionFunc
- func WithSuppressBanner(suppress bool) ServerOptionFunc
- func WithTLS(certFile, keyFile string) ServerOptionFunc
- func WithTemplateDir(dir string) ServerOptionFunc
- func WithTimeouts(readTimeout, writeTimeout, idleTimeout time.Duration) ServerOptionFunc
- func WithWriteTimeout(timeout 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 ¶
var ( Version = "dev" // Version from git tags BuildHash = "unknown" // Git commit hash BuildTime = "unknown" // Build timestamp )
Build information set at compile time using -ldflags
Functions ¶
func DefaultLogger ¶
DefaultLogger returns the logger used by the server package.
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 GetVersionInfo ¶
func GetVersionInfo() string
GetVersionInfo returns formatted version information
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 MCPDev ¶
func MCPDev() mcp.TransportConfig
MCPDev configures MCP with developer tools for local development.
SECURITY WARNING: Only use in development environments. Enables powerful tools that can restart your server and modify its behavior.
Tools provided:
- mcp__hyperserve__server_control
- mcp__hyperserve__route_inspector
- mcp__hyperserve__request_debugger
- mcp__hyperserve__dev_guide
Resources provided:
- logs://server/stream, routes://server/all, requests://debug/recent
func MCPObservability ¶
func MCPObservability() mcp.TransportConfig
MCPObservability configures MCP with observability resources for production use. This preset provides read-only access to system state with no control plane access:
- config://server/current (sanitized server config, no secrets)
- health://server/status (uptime and health metrics)
- logs://server/recent (circular buffer of recent log entries)
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 structured request information. It captures and logs:
- Client IP address
- HTTP method and URL path
- Trace ID (if present in X-Trace-ID header)
- Response status code
- Request duration
- Response size in bytes
This middleware is included by default in NewServer(). For high-traffic applications, consider the performance impact of logging.
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 SetBuiltinPresetHooks ¶ added in v0.25.1
func SetBuiltinPresetHooks(tools, standardResources, observability, developer func(*Server))
SetBuiltinPresetHooks lets pkg/mcp/builtin (and only it, in practice) wire itself into the auto-registration flow used by NewServer when MCP is enabled. Pass nil for any preset you don't implement.
func SetDefaultLogger ¶
SetDefaultLogger overrides the logger used by the server package.
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 AuthTokenInjector ¶
type AuthTokenInjector struct {
// contains filtered or unexported fields
}
AuthTokenInjector adds authentication tokens to requests
func NewAuthTokenInjector ¶
func NewAuthTokenInjector(provider func(context.Context) (string, error)) *AuthTokenInjector
func (*AuthTokenInjector) InterceptRequest ¶
func (ati *AuthTokenInjector) InterceptRequest(ctx context.Context, req *InterceptableRequest) (*InterceptorResponse, error)
func (*AuthTokenInjector) InterceptResponse ¶
func (ati *AuthTokenInjector) InterceptResponse(ctx context.Context, req *InterceptableRequest, resp *InterceptableResponse) error
func (*AuthTokenInjector) Name ¶
func (ati *AuthTokenInjector) Name() string
type CORSOptions ¶
type CORSOptions struct {
AllowedOrigins []string `json:"allowed_origins,omitempty"`
AllowedMethods []string `json:"allowed_methods,omitempty"`
AllowedHeaders []string `json:"allowed_headers,omitempty"`
ExposeHeaders []string `json:"expose_headers,omitempty"`
AllowCredentials bool `json:"allow_credentials,omitempty"`
MaxAgeSeconds int `json:"max_age_seconds,omitempty"`
}
CORSOptions captures configuration for Cross-Origin Resource Sharing handling.
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 InterceptableRequest ¶
type InterceptableRequest struct {
*http.Request
// Metadata can be used to pass data between interceptors
Metadata map[string]any
// contains filtered or unexported fields
}
InterceptableRequest wraps http.Request with additional functionality
func (*InterceptableRequest) GetBody ¶
func (ir *InterceptableRequest) GetBody() ([]byte, error)
GetBody reads and buffers the request body
func (*InterceptableRequest) SetBody ¶
func (ir *InterceptableRequest) SetBody(body []byte)
SetBody sets a new request body
type InterceptableResponse ¶
type InterceptableResponse struct {
http.ResponseWriter
// Response data that can be modified
StatusCode int
Headers http.Header
Body *bytes.Buffer
// Metadata from the request
Metadata map[string]any
}
InterceptableResponse wraps http.ResponseWriter with buffering capability
type Interceptor ¶
type Interceptor interface {
// InterceptRequest is called before the request is processed
// It can modify the request or return an early response
InterceptRequest(ctx context.Context, req *InterceptableRequest) (*InterceptorResponse, error)
// InterceptResponse is called after the response is generated
// It can modify the response before it's sent to the client
InterceptResponse(ctx context.Context, req *InterceptableRequest, resp *InterceptableResponse) error
// Name returns the name of the interceptor for debugging
Name() string
}
Interceptor defines the interface for request/response interceptors
type InterceptorChain ¶
type InterceptorChain struct {
// contains filtered or unexported fields
}
InterceptorChain manages a chain of request/response interceptors
func NewInterceptorChain ¶
func NewInterceptorChain() *InterceptorChain
NewInterceptorChain creates a new interceptor chain
func (*InterceptorChain) Add ¶
func (ic *InterceptorChain) Add(interceptor Interceptor)
Add adds an interceptor to the chain
func (*InterceptorChain) Remove ¶
func (ic *InterceptorChain) Remove(name string) bool
Remove removes an interceptor by name
func (*InterceptorChain) WrapHandler ¶
func (ic *InterceptorChain) WrapHandler(next http.Handler) http.Handler
WrapHandler wraps an http.Handler with the interceptor chain
type InterceptorResponse ¶
InterceptorResponse allows interceptors to return early responses
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 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 RateLimit ¶
RateLimit limits requests per second that can be requested from the httpServer. Requires to add RateLimitMiddleware
type RateLimitInterceptor ¶
type RateLimitInterceptor struct {
// contains filtered or unexported fields
}
RateLimitInterceptor enforces rate limits per client
func NewRateLimitInterceptor ¶
func NewRateLimitInterceptor(limiter RateLimiter) *RateLimitInterceptor
func (*RateLimitInterceptor) InterceptRequest ¶
func (rli *RateLimitInterceptor) InterceptRequest(ctx context.Context, req *InterceptableRequest) (*InterceptorResponse, error)
func (*RateLimitInterceptor) InterceptResponse ¶
func (rli *RateLimitInterceptor) InterceptResponse(ctx context.Context, req *InterceptableRequest, resp *InterceptableResponse) error
func (*RateLimitInterceptor) Name ¶
func (rli *RateLimitInterceptor) Name() string
type RateLimiter ¶
RateLimiter interface for rate limiting
type RequestLogger ¶
type RequestLogger struct {
// contains filtered or unexported fields
}
RequestLogger logs all requests and responses
func NewRequestLogger ¶
func NewRequestLogger(logger func(format string, args ...any)) *RequestLogger
func (*RequestLogger) InterceptRequest ¶
func (rl *RequestLogger) InterceptRequest(ctx context.Context, req *InterceptableRequest) (*InterceptorResponse, error)
func (*RequestLogger) InterceptResponse ¶
func (rl *RequestLogger) InterceptResponse(ctx context.Context, req *InterceptableRequest, resp *InterceptableResponse) error
func (*RequestLogger) Name ¶
func (rl *RequestLogger) Name() string
type ResponseTransformer ¶
type ResponseTransformer struct {
// contains filtered or unexported fields
}
ResponseTransformer modifies response bodies
func NewResponseTransformer ¶
func NewResponseTransformer(transformer func([]byte, string) ([]byte, error)) *ResponseTransformer
func (*ResponseTransformer) InterceptRequest ¶
func (rt *ResponseTransformer) InterceptRequest(ctx context.Context, req *InterceptableRequest) (*InterceptorResponse, error)
func (*ResponseTransformer) InterceptResponse ¶
func (rt *ResponseTransformer) InterceptResponse(ctx context.Context, req *InterceptableRequest, resp *InterceptableResponse) error
func (*ResponseTransformer) Name ¶
func (rt *ResponseTransformer) Name() string
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 with built-in middleware support, health checks, template rendering, and various configuration options.
The Server manages both the main HTTP server and an optional health check server. It handles graceful shutdown, request metrics, and can be extended with custom middleware.
Example:
srv, _ := server.NewServer(
server.WithAddr(":8080"),
server.WithHealthServer(),
)
srv.HandleFunc("/api/users", handleUsers)
srv.Run()
func NewServer ¶
func NewServer(opts ...ServerOptionFunc) (*Server, error)
NewServer creates a new instance of the Server with the given options. By default, the server includes request logging, panic recovery, and metrics collection middleware. The server will listen on ":8080" unless configured otherwise.
Options can be provided to customize the server behavior:
srv, err := server.NewServer(
server.WithAddr(":3000"),
server.WithHealthServer(), // Enable health checks on :8081
server.WithTLS("cert.pem", "key.pem"), // Enable HTTPS
server.WithRateLimit(100, 200), // 100 req/s, burst of 200
)
Returns an error if any of the options fail to apply.
func (*Server) AddMetrics ¶ added in v0.25.1
AddMetrics is a test affordance: it bumps the request count by one and adds to the cumulative response time. See SetMetrics.
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) ClientLimiterCount ¶ added in v0.25.1
ClientLimiterCount returns the number of active per-client rate limiters.
func (*Server) CompleteDeferredInit ¶ added in v0.24.0
CompleteDeferredInit allows applications to manually finalize deferred initialization after addressing failures. Passing a nil error reruns any pending OnReady hooks and marks the server ready. Passing a non-nil error records the failure and leaves the server in an initializing state.
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)
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) IsReady ¶ added in v0.25.1
IsReady reports whether the server is ready to accept traffic.
func (*Server) IsRunning ¶ added in v0.25.1
IsRunning reports whether the server is currently running.
func (*Server) MCPEnabled ¶
MCPEnabled reports whether MCP support has been initialized for this server.
func (*Server) MCPHandler ¶ added in v0.25.1
MCPHandler returns the MCP handler attached to this server, or nil if MCP is not enabled.
func (*Server) MiddlewareRoutes ¶ added in v0.25.1
func (srv *Server) MiddlewareRoutes() map[string]MiddlewareStack
MiddlewareRoutes returns a snapshot of the registered route-to-middleware mapping. The returned map is a shallow copy; mutating it does not affect the server.
func (*Server) Mux ¶ added in v0.25.1
Mux returns the server's underlying http.ServeMux. Exposed so tests can mount the server's handler in an httptest server without going through (*Server).Run.
func (*Server) RegisterMCPExtension ¶
RegisterMCPExtension registers all tools and resources from an extension.
func (*Server) RegisterMCPNamespace ¶
func (srv *Server) RegisterMCPNamespace(name string, configs ...mcp.NamespaceConfig) error
RegisterMCPNamespace registers an entire MCP namespace with its tools and resources.
func (*Server) RegisterMCPResource ¶
RegisterMCPResource registers a custom MCP resource.
func (*Server) RegisterMCPResourceInNamespace ¶
RegisterMCPResourceInNamespace registers a custom MCP resource in the specified namespace.
func (*Server) RegisterMCPTool ¶
RegisterMCPTool registers a custom MCP tool. Must be called after server creation but before Run().
func (*Server) RegisterMCPToolInNamespace ¶
RegisterMCPToolInNamespace registers a custom MCP tool in the specified namespace.
func (*Server) Run ¶
Run starts the server and blocks until a shutdown signal is received. It automatically:
- Starts the main HTTP/HTTPS server
- Starts the health check server (if enabled)
- Sets up graceful shutdown on SIGINT/SIGTERM
- Handles cleanup of resources
- Waits for active requests to complete before shutting down
The method will block until the server is shut down, either by signal or error. Returns an error if the server fails to start or encounters a fatal error.
Example:
if err := srv.Run(); err != nil {
log.Fatal("Server failed:", err)
}
func (*Server) ServerStart ¶ added in v0.25.1
ServerStart returns the timestamp when the server began serving.
func (*Server) SetMetrics ¶ added in v0.25.1
SetMetrics is a test affordance: it overrides the request count and cumulative response time. Production code should never call this; metrics are populated by the request-handling middleware.
func (*Server) TotalRequests ¶ added in v0.25.1
TotalRequests returns the total number of requests served so far.
func (*Server) TotalResponseTime ¶ added in v0.25.1
TotalResponseTime returns the cumulative response time in microseconds.
func (*Server) WebSocketUpgrader ¶
WebSocketUpgrader returns a WebSocket upgrader that tracks connections in server telemetry. Use this instead of creating a standalone Upgrader to ensure WebSocket connections are counted in the server's request metrics.
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 WithBannerColor ¶ added in v0.23.0
func WithBannerColor(enabled bool) ServerOptionFunc
WithBannerColor enables or disables ANSI color output for the startup banner.
func WithCORS ¶
func WithCORS(opts *CORSOptions) ServerOptionFunc
WithCORS configures Cross-Origin Resource Sharing options for HTTP handlers.
func WithCSPWebWorkerSupport ¶
func WithCSPWebWorkerSupport() ServerOptionFunc
WithCSPWebWorkerSupport enables Content Security Policy support for Web Workers using blob: URLs. This is required for modern web applications that use libraries like Tone.js, PDF.js, or other libraries that create Web Workers with blob: URLs for performance optimization. By default, this is disabled for security reasons and must be explicitly enabled.
func WithDebugMode ¶
func WithDebugMode() ServerOptionFunc
WithDebugMode enables debug logging and additional debug features. This is equivalent to WithLoglevel(LevelDebug) plus additional debug information.
func WithDeferredInit ¶ added in v0.23.0
func WithDeferredInit(fn func(context.Context, *Server) error) ServerOptionFunc
WithDeferredInit registers a callback that runs after the server listener is active but before the server is marked ready. While the callback is executing, non-health endpoints receive 503.
func WithDeferredInitStopOnFailure ¶ added in v0.23.0
func WithDeferredInitStopOnFailure(stop bool) ServerOptionFunc
WithDeferredInitStopOnFailure configures whether the server should shut down if the deferred initialization callback returns an error. Defaults to true.
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 WithHardenedMode ¶
func WithHardenedMode() ServerOptionFunc
WithHardenedMode enables hardened security mode for enhanced security headers. In hardened mode, the server header is suppressed and additional security measures are applied.
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 WithIdleTimeout ¶
func WithIdleTimeout(timeout time.Duration) ServerOptionFunc
WithIdleTimeout sets the maximum time to wait for the next request when keep-alives are enabled.
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 WithMCPBuiltinResources ¶
func WithMCPBuiltinResources(enabled bool) ServerOptionFunc
WithMCPBuiltinResources enables the built-in MCP resources (config, metrics, system info, logs) By default, built-in resources are disabled and must be explicitly enabled
func WithMCPBuiltinTools ¶
func WithMCPBuiltinTools(enabled bool) ServerOptionFunc
WithMCPBuiltinTools enables the built-in MCP tools (read_file, list_directory, http_request, calculator) By default, built-in tools are disabled and must be explicitly enabled
func WithMCPDiscoveryFilter ¶
func WithMCPDiscoveryFilter(filter func(toolName string, r *http.Request) bool) ServerOptionFunc
WithMCPDiscoveryFilter sets a custom filter function for MCP discovery.
The filter function receives the tool name and HTTP request, allowing for context-aware filtering based on auth tokens, IP addresses, etc.
Example - Hide admin tools from external requests:
srv, _ := server.NewServer(
server.WithMCPDiscoveryFilter(func(toolName string, r *http.Request) bool {
if strings.Contains(toolName, "admin") {
return strings.HasPrefix(r.RemoteAddr, "10.") ||
strings.HasPrefix(r.RemoteAddr, "192.168.")
}
return true
}),
)
func WithMCPDiscoveryPolicy ¶
func WithMCPDiscoveryPolicy(policy mcp.DiscoveryPolicy) ServerOptionFunc
WithMCPDiscoveryPolicy sets the discovery policy for MCP tools and resources.
Example:
srv, _ := server.NewServer(
server.WithMCPDiscoveryPolicy(mcp.DiscoveryCount),
)
func WithMCPEndpoint ¶
func WithMCPEndpoint(endpoint string) ServerOptionFunc
WithMCPEndpoint configures the MCP endpoint path. Default is "/mcp" if not specified.
func WithMCPFileToolRoot ¶
func WithMCPFileToolRoot(rootDir string) ServerOptionFunc
WithMCPFileToolRoot configures a root directory for MCP file operations. If specified, file tools will be restricted to this directory using os.Root for security.
func WithMCPNamespace ¶
func WithMCPNamespace(name string, configs ...mcp.NamespaceConfig) ServerOptionFunc
WithMCPNamespace registers an additional MCP namespace with tools and resources. This allows you to logically separate tools by domain within a single server instance. Example: WithMCPNamespace("daw", mcp.WithNamespaceTools(playTool, stopTool)) This creates tools accessible as "mcp__daw__play" and "mcp__daw__stop".
func WithMCPSupport ¶
func WithMCPSupport(name, version string, configs ...mcp.TransportConfig) ServerOptionFunc
WithMCPSupport enables MCP (Model Context Protocol) support on the server. This allows AI assistants to connect and use tools/resources provided by the server. Server name and version are required as they identify your server to MCP clients. By default, MCP uses HTTP transport on the "/mcp" endpoint. Example: WithMCPSupport("MyServer", "1.0.0")
func WithOnReady ¶ added in v0.23.0
func WithOnReady(hook func(context.Context, *Server) error) ServerOptionFunc
WithOnReady registers hooks that run after deferred initialization succeeds but before the server is marked ready. Hooks are executed sequentially in the order they were registered.
func WithOnShutdown ¶
func WithOnShutdown(hook func(context.Context) error) ServerOptionFunc
WithOnShutdown registers a function to be called when the server receives a shutdown signal. Multiple hooks can be registered and are executed sequentially in the order they were added. Hooks are called before the HTTP server shutdown begins, allowing applications to cleanly stop their own goroutines and release resources.
Each hook receives a context with a timeout (typically 5 seconds of the total 10-second shutdown budget). Hooks should respect the context deadline and return promptly. Errors from hooks are logged but don't prevent shutdown from proceeding.
Example:
srv, _ := server.NewServer(
server.WithOnShutdown(func(ctx context.Context) error {
log.Println("Stopping background workers...")
return stopWorkers(ctx)
}),
)
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 WithReadHeaderTimeout ¶
func WithReadHeaderTimeout(timeout time.Duration) ServerOptionFunc
WithReadHeaderTimeout sets the amount of time allowed to read request headers. This helps prevent Slowloris attacks.
func WithReadTimeout ¶
func WithReadTimeout(timeout time.Duration) ServerOptionFunc
WithReadTimeout sets the maximum duration for reading the entire request.
func WithSuppressBanner ¶
func WithSuppressBanner(suppress bool) ServerOptionFunc
WithSuppressBanner suppresses the HyperServe ASCII banner at startup. Useful when building white-label products on top of HyperServe.
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. Returns an error if the specified directory does not exist or is not accessible.
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
func WithWriteTimeout ¶
func WithWriteTimeout(timeout time.Duration) ServerOptionFunc
WithWriteTimeout sets the maximum duration before timing out writes of the response.
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"`
ReadHeaderTimeout time.Duration `json:"read_header_timeout,omitempty"`
StaticDir string `json:"static_dir,omitempty"`
TemplateDir string `json:"template_dir,omitempty"`
RunHealthServer bool `json:"run_health_server,omitempty"`
AuthTokenValidatorFunc func(token string) (bool, error)
FIPSMode bool `json:"fips_mode,omitempty"`
HardenedMode bool `json:"hardened_mode,omitempty"`
// MCP (Model Context Protocol) configuration
MCPEnabled bool `json:"mcp_enabled,omitempty"`
MCPEndpoint string `json:"mcp_endpoint,omitempty"`
MCPServerName string `json:"mcp_server_name,omitempty"`
MCPServerVersion string `json:"mcp_server_version,omitempty"`
MCPToolsEnabled bool `json:"mcp_tools_enabled,omitempty"`
MCPResourcesEnabled bool `json:"mcp_resources_enabled,omitempty"`
MCPFileToolRoot string `json:"mcp_file_tool_root,omitempty"`
MCPLogResourceSize int `json:"mcp_log_resource_size,omitempty"`
MCPTransport mcp.TransportType `json:"mcp_transport,omitempty"`
MCPDev bool `json:"mcp_dev,omitempty"`
MCPObservability bool `json:"mcp_observability,omitempty"`
MCPDiscoveryPolicy mcp.DiscoveryPolicy `json:"mcp_discovery_policy,omitempty"`
MCPDiscoveryFilter func(toolName string, r *http.Request) bool `json:"-"` // Custom filter function
// CSP (Content Security Policy) configuration
CSPWebWorkerSupport bool `json:"csp_web_worker_support,omitempty"`
CORS *CORSOptions `json:"cors,omitempty"`
// Logging configuration
LogLevel string `json:"log_level,omitempty"`
DebugMode bool `json:"debug_mode,omitempty"`
// Banner configuration
SuppressBanner bool `json:"suppress_banner,omitempty"`
BannerColor bool `json:"banner_color,omitempty"`
// OnShutdownHooks are functions called when the server receives a shutdown signal.
// Hooks are executed sequentially in the order they were added, before HTTP server shutdown.
// Each hook receives a context with timeout and should respect the deadline.
// Errors from hooks are logged but don't prevent shutdown.
OnShutdownHooks []func(context.Context) error `json:"-"`
// DeferredInit is an optional callback that runs after the server listener is up but before
// the server is marked ready. While it executes, regular handlers return 503 responses.
DeferredInit func(context.Context, *Server) error `json:"-"`
// OnReadyHooks run after deferred initialization succeeds and before the server is marked ready.
OnReadyHooks []func(context.Context, *Server) error `json:"-"`
// StopOnDeferredInitFailure indicates whether the server should shut down if deferred init fails.
StopOnDeferredInitFailure bool `json:"stop_on_deferred_init_failure,omitempty"`
// contains filtered or unexported fields
}
ServerOptions contains all configuration settings for the HTTP server. Options can be set via WithXXX functions when creating a new server, environment variables, or a configuration file.
Zero values are sensible defaults for most applications.
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.