Documentation
¶
Overview ¶
Package httpserver provides a configurable, reloadable HTTP server implementation that can be managed by the supervisor package.
This file defines the core middleware execution types.
RequestProcessor manages the middleware chain execution and provides access to request/response data. It handles the control flow ("when" middleware runs) while ResponseWriter (response_writer.go) handles data capture ("what" data is available).
When writing custom middleware, use RequestProcessor methods to: - Continue processing: rp.Next() - Stop processing: rp.Abort() - Access request: rp.Request() - Access response: rp.Writer()
Package httpserver provides HTTP server functionality with middleware support.
This file defines ResponseWriter, which wraps the standard http.ResponseWriter to capture response metadata that the standard interface doesn't expose.
Why This Wrapper Exists ¶
The standard http.ResponseWriter doesn't provide access to the status code or byte count after they've been written. Middleware needs this information for logging, metrics, and conditional processing.
Relationship to Middleware ¶
Middleware functions receive a RequestProcessor that contains this ResponseWriter. The wrapper allows middleware to inspect response state after handlers execute.
Relationship to RequestProcessor (context.go) ¶
RequestProcessor manages middleware execution flow and provides access to this ResponseWriter through its Writer() method. The RequestProcessor handles the "when" of middleware execution, while ResponseWriter handles the "what" of response data capture.
Index ¶
- Variables
- type Config
- type ConfigCallback
- type ConfigOption
- func WithConfigCopy(src *Config) ConfigOption
- func WithDrainTimeout(timeout time.Duration) ConfigOption
- func WithIdleTimeout(timeout time.Duration) ConfigOption
- func WithReadTimeout(timeout time.Duration) ConfigOption
- func WithRequestContext(ctx context.Context) ConfigOption
- func WithServerCreator(creator ServerCreator) ConfigOption
- func WithWriteTimeout(timeout time.Duration) ConfigOption
- type HandlerFunc
- type HttpServer
- type Option
- type RequestProcessor
- type ResponseWriter
- type Route
- type Routes
- type Runner
- func (r *Runner) GetState() string
- func (r *Runner) GetStateChan(ctx context.Context) <-chan string
- func (r *Runner) GetStateChanWithTimeout(ctx context.Context) <-chan string
- func (r *Runner) IsRunning() bool
- func (r *Runner) Reload()
- func (r *Runner) Run(ctx context.Context) error
- func (r *Runner) Stop()
- func (r *Runner) String() string
- type ServerCreator
Constants ¶
This section is empty.
Variables ¶
var ( ErrNoConfig = errors.New("no config provided") ErrNoHandlers = errors.New("no handlers provided") ErrGracefulShutdown = errors.New("graceful shutdown failed") ErrGracefulShutdownTimeout = errors.New("graceful shutdown deadline reached") ErrHttpServer = errors.New("http server error") ErrOldConfig = errors.New("config hasn't changed since last update") ErrRetrieveConfig = errors.New("failed to retrieve server configuration") ErrCreateConfig = errors.New("failed to create server configuration") ErrServerNotRunning = errors.New("http server is not running") ErrServerReadinessTimeout = errors.New("server readiness check timed out") ErrServerBoot = errors.New("failed to start HTTP server") ErrConfigCallbackNil = errors.New("config callback returned nil") ErrConfigCallback = errors.New("failed to load configuration from callback") ErrStateTransition = errors.New("state transition failed") )
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct { // Core configuration ListenAddr string DrainTimeout time.Duration Routes Routes // Server settings ReadTimeout time.Duration WriteTimeout time.Duration IdleTimeout time.Duration // Server creation callback function ServerCreator ServerCreator // contains filtered or unexported fields }
Config is the main configuration struct for the HTTP server
func NewConfig ¶
func NewConfig(addr string, routes Routes, opts ...ConfigOption) (*Config, error)
NewConfig creates a new Config with the address and routes plus any optional configuration via functional options
type ConfigCallback ¶
ConfigCallback is the function type signature for the callback used to load initial config, and new config during Reload()
type ConfigOption ¶
type ConfigOption func(*Config)
ConfigOption defines a functional option for configuring Config
func WithConfigCopy ¶
func WithConfigCopy(src *Config) ConfigOption
WithConfigCopy creates a ConfigOption that copies most settings from the source config except for ListenAddr and Routes which are provided directly to NewConfig.
func WithDrainTimeout ¶
func WithDrainTimeout(timeout time.Duration) ConfigOption
WithDrainTimeout sets the drain timeout for graceful shutdown
func WithIdleTimeout ¶
func WithIdleTimeout(timeout time.Duration) ConfigOption
WithIdleTimeout sets the idle timeout for the HTTP server
func WithReadTimeout ¶
func WithReadTimeout(timeout time.Duration) ConfigOption
WithReadTimeout sets the read timeout for the HTTP server
func WithRequestContext ¶
func WithRequestContext(ctx context.Context) ConfigOption
WithRequestContext sets the context that will be propagated to all request handlers via http.Server's BaseContext. This allows handlers to be aware of server shutdown.
func WithServerCreator ¶
func WithServerCreator(creator ServerCreator) ConfigOption
WithServerCreator sets a custom server creator for the HTTP server
func WithWriteTimeout ¶
func WithWriteTimeout(timeout time.Duration) ConfigOption
WithWriteTimeout sets the write timeout for the HTTP server
type HandlerFunc ¶ added in v0.0.10
type HandlerFunc func(*RequestProcessor)
HandlerFunc is the middleware/handler signature
type HttpServer ¶
HttpServer is the interface for the HTTP server
func DefaultServerCreator ¶
func DefaultServerCreator(addr string, handler http.Handler, cfg *Config) HttpServer
DefaultServerCreator creates a standard http.Server instance with the settings from Config
type Option ¶
type Option func(*Runner)
Option represents a functional option for configuring Runner.
func WithConfig ¶
WithConfig sets the initial configuration for the Runner instance. This option wraps the WithConfigCallback option, allowing you to pass a Config instance directly instead of a callback function. This is useful when you have a static configuration that doesn't require dynamic loading or reloading.
func WithConfigCallback ¶
func WithConfigCallback(callback ConfigCallback) Option
WithConfigCallback sets the function that will be called to load or reload configuration. Either this option or WithConfig initializes the Runner instance by providing the configuration for the HTTP server managed by the Runner.
func WithLogHandler ¶
WithLogHandler sets a custom slog handler for the Runner instance. For example, to use a custom JSON handler with debug level:
handler := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}) runner, err := httpserver.NewRunner(ctx, httpserver.WithConfigCallback(configCallback), httpserver.WithLogHandler(handler))
type RequestProcessor ¶ added in v0.0.10
type RequestProcessor struct {
// contains filtered or unexported fields
}
RequestProcessor carries the request/response and middleware chain
func (*RequestProcessor) Abort ¶ added in v0.0.10
func (rp *RequestProcessor) Abort()
Abort prevents remaining handlers from being called
func (*RequestProcessor) IsAborted ¶ added in v0.0.10
func (rp *RequestProcessor) IsAborted() bool
IsAborted returns true if the request processing was aborted
func (*RequestProcessor) Next ¶ added in v0.0.10
func (rp *RequestProcessor) Next()
Next executes the remaining handlers in the chain
func (*RequestProcessor) Request ¶ added in v0.0.10
func (rp *RequestProcessor) Request() *http.Request
Request returns the HTTP request
func (*RequestProcessor) SetWriter ¶ added in v0.0.10
func (rp *RequestProcessor) SetWriter(w ResponseWriter)
SetWriter replaces the ResponseWriter for the request. This allows middleware to intercept and transform responses.
func (*RequestProcessor) Writer ¶ added in v0.0.10
func (rp *RequestProcessor) Writer() ResponseWriter
Writer returns the ResponseWriter for the request
type ResponseWriter ¶ added in v0.0.10
type ResponseWriter interface { http.ResponseWriter // Status returns the HTTP status code Status() int // Written returns true if the response has been written Written() bool // Size returns the number of bytes written Size() int }
ResponseWriter wraps http.ResponseWriter with additional functionality
type Route ¶
type Route struct { Path string Handlers []HandlerFunc // contains filtered or unexported fields }
Route represents a single HTTP route with a name, path, and handler chain.
func NewRouteFromHandlerFunc ¶ added in v0.0.10
func NewRouteFromHandlerFunc( name string, path string, handler http.HandlerFunc, middlewares ...HandlerFunc, ) (*Route, error)
NewRouteFromHandlerFunc creates a new Route with the given name, path, and handler. Optionally, it can include middleware functions. This is the preferred way to create routes in the httpserver package.
type Routes ¶
type Routes []Route
Routes is a map of paths as strings, that route to http.HandlerFuncs
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner implements an HTTP server with graceful shutdown, dynamic reconfiguration, and state monitoring. It implements the Runnable, Reloadable, and Stateable interfaces from the supervisor package.
func (*Runner) GetStateChan ¶
GetStateChan returns a channel that emits the HTTP server's state whenever it changes. The channel is closed when the provided context is canceled.
func (*Runner) GetStateChanWithTimeout ¶ added in v0.0.12
GetStateChanWithTimeout returns a channel that emits state changes. The channel is closed when the provided context is canceled.
func (*Runner) Reload ¶
func (r *Runner) Reload()
Reload refreshes the server configuration and restarts the HTTP server if necessary. This method is safe to call while the server is running and will handle graceful shutdown and restart.
func (*Runner) Run ¶
Run starts the HTTP server and handles its lifecycle. It transitions through FSM states and returns when the server is stopped or encounters an error.
type ServerCreator ¶
type ServerCreator func(addr string, handler http.Handler, cfg *Config) HttpServer
ServerCreator is a function type that creates an HttpServer instance