server

package
v1.6.1 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Overview

Package server provides a net/http-shaped Go server with lifecycle, middleware, typed request binding, WebSocket integration, and optional Model Context Protocol (MCP) endpoints. Routes use http.ServeMux patterns, and handlers remain http.Handler values.

Use net/http directly when routes plus JSON are sufficient. Package server is useful when an application would otherwise assemble the same timeout, recovery, graceful shutdown, readiness, input, and protocol plumbing itself.

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

View Source
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 Bind added in v0.27.0

func Bind(r *http.Request, dst any) error

Bind picks the decoder based on Content-Type:

  • application/json → BindJSON
  • application/x-www-form-urlencoded or multipart/form-data → BindForm
  • otherwise → BindQuery

func BindForm added in v0.27.0

func BindForm(r *http.Request, dst any) error

BindForm decodes application/x-www-form-urlencoded or multipart/form-data into dst, then runs Validate.

func BindJSON added in v0.27.0

func BindJSON(r *http.Request, dst any) error

BindJSON decodes the request body as JSON into dst, then runs Validate. dst must be a non-nil pointer to a struct. Returns ValidationError when rules fail, and the wrapped error otherwise (decode error, etc.).

func BindQuery added in v0.27.0

func BindQuery(r *http.Request, dst any) error

BindQuery decodes URL query parameters into dst (string keys → struct fields by json tag or lowercased name). Slices are populated from repeated keys. Then runs Validate.

func DefaultLogger

func DefaultLogger() *slog.Logger

DefaultLogger returns the logger used by the server package.

func EnsureTrailingSlash

func EnsureTrailingSlash(dir string) string

EnsureTrailingSlash ensures that a directory path ends with a trailing slash.

func JSONEcho added in v0.30.0

func JSONEcho[T any]() http.HandlerFunc

JSONEcho is the shorthand for the validate-and-pass-through case: bind the body into T, run validation, and echo the validated value back as the 200 response. Useful for webhook acks, dev stubs, and "did this payload validate?" endpoints where the response shape is the same as the input.

srv.POST("/users", server.JSONEcho[CreateUser]())

Reach for JSONHandler[In, Out] when the response is genuinely different from the input — assigning a server-side ID, lowercasing the email, joining a related record. An identity function is the absence of business logic; JSONEcho says so directly.

Errors follow JSONHandler: *ValidationError → per-field 400 envelope, other bind errors → 400 with {"error": err.Error()}.

func JSONHandler added in v0.29.0

func JSONHandler[In, Out any](fn func(context.Context, In) (Out, error)) http.HandlerFunc

JSONHandler wraps a typed business function as an http.HandlerFunc. It performs bind + validate + invoke + respond in a single step so handlers only contain business logic.

srv.HandleFunc("POST /users", server.JSONHandler(
    func(ctx context.Context, in CreateUser) (User, error) {
        return createUser(ctx, in)
    },
))

func MCPDev

func MCPDev() mcp.TransportConfig

MCPDev configures MCP with developer tools for local development.

SECURITY WARNING: Only use in development environments. Enables tools that can modify server behavior (log level, route introspection).

Tools provided:

  • mcp__hyperserve__server_control
  • mcp__hyperserve__route_inspector
  • mcp__hyperserve__dev_guide

Resources provided:

  • logs://server/stream, routes://server/all

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

func SetDefaultLogger(l *slog.Logger)

SetDefaultLogger overrides the logger used by the server package.

func Validate added in v0.27.0

func Validate(dst any) error

Validate runs `validate:"..."` rules over dst (must be a pointer to a struct or a struct). Returns a *ValidationError when any rule fails, or nil otherwise. Nested structs are recursed into; pointers are dereferenced.

func VersionInfo added in v0.33.0

func VersionInfo() string

VersionInfo returns formatted version information

Types

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

type DataFunc func(r *http.Request) any

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 FieldError added in v0.27.0

type FieldError = validate.FieldError

FieldError describes one failed validation rule. Aliased to the internal/validate type so pkg/mcp can produce the same errors when validating typed-tool arguments.

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

type RateLimit = rate.Limit

RateLimit limits requests per second that can be requested from the httpServer. Requires to add RateLimitMiddleware

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. Multi-line data is emitted as one data field per line.

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

func (srv *Server) AddMetrics(deltaRequests uint64, deltaResponseTime int64)

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

func (srv *Server) ClientLimiterCount() int

ClientLimiterCount returns the number of active per-client rate limiters.

func (*Server) CompleteDeferredInit added in v0.24.0

func (srv *Server) CompleteDeferredInit(ctx context.Context, err error) error

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) DELETE added in v0.29.0

func (srv *Server) DELETE(pattern string, handler http.HandlerFunc)

DELETE registers handler for DELETE requests matching pattern.

func (*Server) GET added in v0.29.0

func (srv *Server) GET(pattern string, handler http.HandlerFunc)

GET registers handler for GET requests matching pattern.

func (*Server) HEAD added in v0.29.0

func (srv *Server) HEAD(pattern string, handler http.HandlerFunc)

HEAD registers handler for HEAD requests matching pattern.

func (*Server) Handle

func (srv *Server) Handle(pattern string, handler http.Handler)

Handle registers an http.Handler for the given pattern. Mirrors http.ServeMux.Handle but also tracks the pattern so middleware stacks applied via AddMiddlewareStack can find it. Use this when you have an existing http.Handler (e.g., http.FileServer); use HandleFunc for inline handler functions.

srv.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))

func (*Server) HandleFunc

func (srv *Server) HandleFunc(pattern string, handler http.HandlerFunc)

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 deprecated

func (srv *Server) HandleStatic(pattern string)

HandleStatic registers a handler that serves files only through an os.Root confined to Options.StaticDir. A root-open failure is logged and leaves the route unregistered.

Deprecated: use HandleStaticChecked to handle setup failures explicitly.

func (*Server) HandleStaticChecked added in v1.5.0

func (srv *Server) HandleStaticChecked(pattern string) error

HandleStaticChecked registers a handler that serves files only through an os.Root confined to Options.StaticDir. It returns an error without registering the route if the configured root cannot be opened.

func (*Server) HandleTemplate

func (srv *Server) HandleTemplate(pattern, t string, data any) 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) Handler

func (srv *Server) Handler() http.Handler

func (*Server) IsReady added in v0.25.1

func (srv *Server) IsReady() bool

IsReady reports whether the server is ready to accept traffic.

func (*Server) IsRunning added in v0.25.1

func (srv *Server) IsRunning() bool

IsRunning reports whether the server is currently running.

func (*Server) MCPEnabled

func (srv *Server) MCPEnabled() bool

MCPEnabled reports whether MCP support has been initialized for this server.

func (*Server) MCPHandler added in v0.25.1

func (srv *Server) MCPHandler() *mcp.Handler

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

func (srv *Server) Mux() *http.ServeMux

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) OPTIONS added in v0.29.0

func (srv *Server) OPTIONS(pattern string, handler http.HandlerFunc)

OPTIONS registers handler for OPTIONS requests matching pattern.

func (*Server) PATCH added in v0.29.0

func (srv *Server) PATCH(pattern string, handler http.HandlerFunc)

PATCH registers handler for PATCH requests matching pattern.

func (*Server) POST added in v0.29.0

func (srv *Server) POST(pattern string, handler http.HandlerFunc)

POST registers handler for POST requests matching pattern.

func (*Server) PUT added in v0.29.0

func (srv *Server) PUT(pattern string, handler http.HandlerFunc)

PUT registers handler for PUT requests matching pattern.

func (*Server) RegisterMCPExtension

func (srv *Server) RegisterMCPExtension(ext mcp.Extension) error

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. Per-tool/per-resource namespace registration goes through this path — callers that need a single tool in a namespace pass it inside a NamespaceConfig rather than reaching for two separate helpers.

func (*Server) RegisterMCPResource

func (srv *Server) RegisterMCPResource(resource mcp.Resource) error

RegisterMCPResource registers a custom MCP resource.

func (*Server) RegisterMCPResourceTemplate added in v1.2.0

func (srv *Server) RegisterMCPResourceTemplate(template mcp.ResourceTemplate) error

RegisterMCPResourceTemplate registers a custom MCP resource template.

func (*Server) RegisterMCPTool

func (srv *Server) RegisterMCPTool(tool mcp.Tool) error

RegisterMCPTool registers a custom MCP tool. Must be called after server creation but before Run().

func (*Server) RegisteredRoutes added in v1.1.0

func (srv *Server) RegisteredRoutes() []string

RegisteredRoutes returns a sorted snapshot of patterns registered through Handle, HandleFunc, and the method-aware route helpers.

func (*Server) Run

func (srv *Server) Run() error

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) RunContext added in v1.5.0

func (srv *Server) RunContext(ctx context.Context) error

RunContext starts the HTTP/HTTPS server and blocks until ctx requests a graceful shutdown, the server exits, or deferred initialization fails. It does not subscribe to process signals; the caller owns the lifecycle. Cancellation is a normal shutdown trigger and returns nil when shutdown succeeds. RunContext returns an error for MCP stdio transport because a context cannot portably interrupt its blocking stdin read; use Run and EOF. A Server must not be run concurrently or reused after RunContext returns.

func (*Server) ServerStart added in v0.25.1

func (srv *Server) ServerStart() time.Time

ServerStart returns the timestamp when the server began serving.

func (*Server) SetMetrics added in v0.25.1

func (srv *Server) SetMetrics(totalRequests uint64, totalResponseTime int64)

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

func (srv *Server) Stop() error

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

func (*Server) TotalRequests added in v0.25.1

func (srv *Server) TotalRequests() uint64

TotalRequests returns the total number of requests served so far.

func (*Server) TotalResponseTime added in v0.25.1

func (srv *Server) TotalResponseTime() int64

TotalResponseTime returns the cumulative response time in microseconds.

func (*Server) WebSocketUpgrader

func (srv *Server) WebSocketUpgrader() *websocket.Upgrader

WebSocketUpgrader returns a WebSocket upgrader that tracks the upgrade in server telemetry. Use this instead of a standalone Upgrader so WS upgrades land in totalWebSocketUpgrades alongside the totalRequests counter that MetricsMiddleware already maintains for every request.

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 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 WithConfigFile added in v1.5.0

func WithConfigFile(path string) ServerOptionFunc

WithConfigFile overlays fields present in the JSON file at path. An explicit file is required to exist and contain one valid JSON object.

func WithDebugMode

func WithDebugMode() ServerOptionFunc

WithDebugMode enables debug logging and additional debug features. (The previously-exported WithLoglevel had no callers; use WithDebugMode or the HS_LOG_LEVEL env var to change the log level.)

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 WithEnvironment added in v1.5.0

func WithEnvironment() ServerOptionFunc

WithEnvironment overlays supported SERVER_ADDR, HEALTH_ADDR, and HS_* variables. It does not consult HS_CONFIG_PATH; use WithConfigFile when the application chooses to read a file.

func WithFIPSMode

func WithFIPSMode() ServerOptionFunc

WithFIPSMode restricts the TLS handshake to FIPS-approved cipher suites and elliptic curves.

This is NOT full FIPS 140-3 compliance:

  • it does not switch the Go toolchain into FIPS mode (build with GOFIPS140 for that);
  • it does not constrain non-TLS crypto (hashes, RNGs, signatures outside TLS);
  • it does not invoke a FIPS-validated cryptographic module.

Use this for "TLS handshake uses FIPS-approved primitives." For deployments that require true FIPS 140-3 compliance, combine with a FIPS-validated toolchain build.

func WithHardenedMode deprecated

func WithHardenedMode() ServerOptionFunc

WithHardenedMode preserves the former server-identification opt-out. Server identification is now omitted by default.

Deprecated: leave ServerHeader empty instead.

func WithHealthAddr added in v1.1.0

func WithHealthAddr(addr string) ServerOptionFunc

WithHealthAddr sets the address for the separate health server.

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 WithLogLevel added in v1.1.0

func WithLogLevel(level string) ServerOptionFunc

WithLogLevel sets the configured server log level. Accepted values are DEBUG, INFO, WARN, and ERROR.

func WithMCPBuiltinResources

func WithMCPBuiltinResources(enabled bool) ServerOptionFunc

WithMCPBuiltinResources toggles the built-in MCP resources (Config, Metrics, System, ServerLog, ServerHealth). Default off. Same blank-import requirement as WithMCPBuiltinTools.

func WithMCPBuiltinTools

func WithMCPBuiltinTools(enabled bool) ServerOptionFunc

WithMCPBuiltinTools toggles the built-in MCP tools (Calculator plus sandboxed FileRead / ListDirectory when WithMCPFileToolRoot is set). Default off. Requires `_ "github.com/osauer/hyperserve/pkg/mcp/builtin"` to be blank-imported by the consumer; otherwise NewServer logs a warning and registers nothing.

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".

func WithMCPFileToolRoot

func WithMCPFileToolRoot(rootDir string) ServerOptionFunc

WithMCPFileToolRoot scopes MCP file tools to rootDir via os.Root, so they cannot read or list paths outside it.

func WithMCPLegacyRoutedSSE deprecated added in v1.4.0

func WithMCPLegacyRoutedSSE(enabled bool) ServerOptionFunc

WithMCPLegacyRoutedSSE enables HyperServe's proprietary X-SSE-* routed transport. It is disabled by default and should be used only while clients migrate to MCP 2026-07-28 Streamable HTTP subscriptions/listen.

Deprecated: use MCP 2026-07-28 Streamable HTTP.

func WithMCPOriginValidator added in v1.4.0

func WithMCPOriginValidator(validator func(*http.Request) bool) ServerOptionFunc

WithMCPOriginValidator overrides MCP's default same-origin browser policy. The validator receives every MCP request and should allow requests without Origin when non-browser clients are expected. Use an explicit allowlist and do not trust Origin as authentication. Passing nil restores the default.

func WithMCPProtocolVersion added in v1.2.0

func WithMCPProtocolVersion(version string) ServerOptionFunc

WithMCPProtocolVersion overrides the MCP protocol version advertised to clients. Empty values reset to mcp.DefaultProtocolVersion.

func WithMCPSupport

func WithMCPSupport(name, version string, configs ...mcp.TransportConfig) ServerOptionFunc

WithMCPSupport enables MCP (Model Context Protocol) support on the server. Server name and version identify the server to MCP clients. By default, MCP uses HTTP transport on the "/mcp" endpoint; pass mcp.TransportConfig values to switch to stdio or to install a preset (DeveloperMode, ObservabilityMode).

Example:

server.NewServer(server.WithMCPSupport("MyServer", "1.0.0"))

func WithMCPToolCallTimeout added in v0.27.0

func WithMCPToolCallTimeout(d time.Duration) ServerOptionFunc

WithMCPToolCallTimeout sets the per-tool execution budget enforced by the MCP handler. Tools that exceed the timeout return context.DeadlineExceeded to the caller; see the caveat in contextToolWrapper for what happens to the underlying goroutine. Zero or negative values fall back to the package default (30s).

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 WithOptions added in v1.5.0

func WithOptions(options ServerOptions) ServerOptionFunc

WithOptions replaces the current option snapshot with a defensive copy of options. Options passed later to NewServer override this snapshot.

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 WithServerHeader added in v1.5.0

func WithServerHeader(value string) ServerOptionFunc

WithServerHeader opts into a Server response header when HeadersMiddleware is installed. The empty string omits identification. Invalid HTTP control bytes cause NewServer to return an error.

func WithStartupBanner added in v1.5.0

func WithStartupBanner() ServerOptionFunc

WithStartupBanner opts into HyperServe's ASCII startup banner. Library consumers are silent by default apart from configured structured logs.

func WithStaticDir added in v1.6.0

func WithStaticDir(dir string) ServerOptionFunc

WithStaticDir sets the directory root used by Server.HandleStaticChecked. The directory is opened and validated when the static route is registered.

func WithSuppressBanner deprecated

func WithSuppressBanner(suppress bool) ServerOptionFunc

WithSuppressBanner controls the legacy inverse banner setting.

Deprecated: the banner is suppressed by default; use WithStartupBanner to opt in.

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

type ServerOptions

type ServerOptions struct {
	Addr                   string        `json:"addr,omitempty"`
	EnableTLS              bool          `json:"tls,omitempty"`
	TLSAddr                string        `json:"tls_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"`
	// ServerHeader is emitted by HeadersMiddleware when non-empty.
	ServerHeader string `json:"server_header,omitempty"`
	// HardenedMode is the legacy representation of an omitted Server header.
	// Deprecated: leave ServerHeader empty instead.
	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"`
	MCPToolCallTimeout  time.Duration                               `json:"mcp_tool_call_timeout,omitempty"`
	MCPTransport        mcp.TransportType                           `json:"mcp_transport,omitempty"`
	MCPProtocolVersion  string                                      `json:"mcp_protocol_version,omitempty"`
	MCPLegacyRoutedSSE  bool                                        `json:"mcp_legacy_routed_sse,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
	MCPOriginValidator  func(r *http.Request) bool                  `json:"-"`

	// 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:"-"`

	// 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. Bind a configuration file or environment variables explicitly with WithConfigFile or WithEnvironment.

Use DefaultServerOptions to obtain HyperServe's defaults before modifying a complete snapshot; a zero ServerOptions value is not implicitly filled.

func DefaultServerOptions added in v1.5.0

func DefaultServerOptions() ServerOptions

DefaultServerOptions returns an independent copy of HyperServe's deterministic defaults. Nested slices and CORS configuration are cloned so callers may safely modify the result before passing it to WithOptions.

func NewServerOptions deprecated

func NewServerOptions() *ServerOptions

NewServerOptions returns defaults overlaid by the legacy implicit options.json/HS_CONFIG_PATH file and process environment configuration. New code should compose WithConfigFile and WithEnvironment explicitly.

Deprecated: use DefaultServerOptions, WithConfigFile, and WithEnvironment.

type StatusError added in v0.29.0

type StatusError struct {
	Code    int
	Message string
	Err     error
}

StatusError carries an HTTP status code so handler errors can opt into a specific 4xx/5xx response without inventing a new error type per call site. Use NewStatusError, or any error that implements `HTTPStatus() int`.

func NewStatusError added in v0.29.0

func NewStatusError(code int, message string) *StatusError

NewStatusError builds a StatusError. Message is the public string sent in the response body; pass an empty message to fall back to http.StatusText.

func (*StatusError) Error added in v0.29.0

func (e *StatusError) Error() string

Error implements error.

func (*StatusError) HTTPStatus added in v0.29.0

func (e *StatusError) HTTPStatus() int

HTTPStatus is the contract JSONHandler keys off when mapping handler errors to response codes.

func (*StatusError) Unwrap added in v0.29.0

func (e *StatusError) Unwrap() error

Unwrap exposes the inner cause for errors.Is / errors.As.

type ValidationError added in v0.27.0

type ValidationError = validate.ValidationError

ValidationError is the aggregate error returned by Validate / Bind* when one or more fields fail their rules. Aliased to internal/validate.

Jump to

Keyboard shortcuts

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