Documentation
¶
Overview ¶
Package httpserver provides an HTTP server module for the modular framework.
Package httpserver provides an HTTP server module for the modular framework.
Package httpserver provides an HTTP server module for the modular framework. This module offers a complete HTTP server implementation with support for TLS, automatic certificate management, graceful shutdown, and middleware integration.
The httpserver module features:
- HTTP and HTTPS server support
- Automatic TLS certificate generation and management
- Configurable timeouts and limits
- Graceful shutdown handling
- Handler registration and middleware support
- Health check endpoints
- Integration with Let's Encrypt for automatic certificates
Usage:
app.RegisterModule(httpserver.NewModule())
The module registers an HTTP server service that can be used by other modules to register handlers, middleware, or access the underlying server instance.
Configuration:
The module requires an "httpserver" configuration section with server settings including address, ports, TLS configuration, and timeout values.
Index ¶
- Constants
- Variables
- func NewHTTPServerModule() modular.Module
- type CertificateService
- type HTTPServerConfig
- type HTTPServerModule
- func (m *HTTPServerModule) Constructor() modular.ModuleConstructor
- func (m *HTTPServerModule) EmitEvent(ctx context.Context, event cloudevents.Event) error
- func (m *HTTPServerModule) GetRegisteredEventTypes() []string
- func (m *HTTPServerModule) Init(app modular.Application) error
- func (m *HTTPServerModule) Name() string
- func (m *HTTPServerModule) ProvidesServices() []modular.ServiceProvider
- func (m *HTTPServerModule) RegisterConfig(app modular.Application) error
- func (m *HTTPServerModule) RegisterObservers(subject modular.Subject) error
- func (m *HTTPServerModule) RequiresServices() []modular.ServiceDependency
- func (m *HTTPServerModule) Start(ctx context.Context) error
- func (m *HTTPServerModule) Stop(ctx context.Context) error
- type TLSConfig
Constants ¶
const ( // Server lifecycle events EventTypeServerStarted = "com.modular.httpserver.server.started" EventTypeServerStopped = "com.modular.httpserver.server.stopped" // Request handling events EventTypeRequestReceived = "com.modular.httpserver.request.received" EventTypeRequestHandled = "com.modular.httpserver.request.handled" // TLS events EventTypeTLSEnabled = "com.modular.httpserver.tls.enabled" EventTypeTLSConfigured = "com.modular.httpserver.tls.configured" // Configuration events EventTypeConfigLoaded = "com.modular.httpserver.config.loaded" )
Event type constants for httpserver module events. Following CloudEvents specification reverse domain notation.
const DefaultTimeout = 15 * time.Second
DefaultTimeout is the default timeout value
const ModuleName = "httpserver"
ModuleName is the name of this module for registration and dependency resolution.
Variables ¶
var ( ErrInvalidPort = errors.New("invalid port number") ErrTLSNoDomainsSpecified = errors.New("TLS auto-generation is enabled but no domains specified") ErrTLSNoCertificateFile = errors.New("TLS is enabled but no certificate file specified") ErrTLSNoKeyFile = errors.New("TLS is enabled but no key file specified") )
Static errors for configuration validation
var ( // ErrServerNotStarted is returned when attempting to stop a server that hasn't been started. ErrServerNotStarted = errors.New("server not started") // ErrNoHandler is returned when no HTTP handler is available for the server. ErrNoHandler = errors.New("no HTTP handler available") // ErrRouterServiceNotHandler is returned when the router service doesn't implement http.Handler. ErrRouterServiceNotHandler = errors.New("router service does not implement http.Handler") // ErrServerStartTimeout is returned when the server fails to start within the timeout period. ErrServerStartTimeout = errors.New("context cancelled while waiting for server to start") )
Error definitions for HTTP server operations.
var ( // ErrNoSubjectForEventEmission is returned when trying to emit events without a subject ErrNoSubjectForEventEmission = errors.New("no subject available for event emission") )
Error definitions
Functions ¶
func NewHTTPServerModule ¶
NewHTTPServerModule creates a new instance of the HTTP server module. The returned module must be registered with the application before use.
Example:
httpModule := httpserver.NewHTTPServerModule() app.RegisterModule(httpModule)
Types ¶
type CertificateService ¶
type CertificateService interface { // GetCertificate returns a certificate for the given ClientHello GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error) }
CertificateService defines the interface for a service that can provide TLS certificates
type HTTPServerConfig ¶
type HTTPServerConfig struct { // Host is the hostname or IP address to bind to. Host string `yaml:"host" json:"host" env:"HOST"` // Port is the port number to listen on. Port int `yaml:"port" json:"port" env:"PORT"` // ReadTimeout is the maximum duration for reading the entire request, // including the body. ReadTimeout time.Duration `yaml:"read_timeout" json:"read_timeout" env:"READ_TIMEOUT"` // WriteTimeout is the maximum duration before timing out writes of the response. WriteTimeout time.Duration `yaml:"write_timeout" json:"write_timeout" env:"WRITE_TIMEOUT"` // IdleTimeout is the maximum amount of time to wait for the next request. IdleTimeout time.Duration `yaml:"idle_timeout" json:"idle_timeout" env:"IDLE_TIMEOUT"` // ShutdownTimeout is the maximum amount of time to wait during graceful // shutdown. ShutdownTimeout time.Duration `yaml:"shutdown_timeout" json:"shutdown_timeout" env:"SHUTDOWN_TIMEOUT"` // TLS configuration if HTTPS is enabled TLS *TLSConfig `yaml:"tls" json:"tls"` }
HTTPServerConfig defines the configuration for the HTTP server module.
func (*HTTPServerConfig) Validate ¶
func (c *HTTPServerConfig) Validate() error
Validate checks if the configuration is valid and sets default values where appropriate.
type HTTPServerModule ¶
type HTTPServerModule struct {
// contains filtered or unexported fields
}
HTTPServerModule represents the HTTP server module and implements the modular.Module interface. It provides a complete HTTP server implementation with TLS support, graceful shutdown, and integration with the modular framework's configuration and service systems.
The module manages:
- HTTP server lifecycle (start, stop, graceful shutdown)
- TLS certificate management and automatic generation
- Request routing and handler registration
- Server configuration and health monitoring
- Integration with certificate services for automatic HTTPS
- Event observation and emission for server operations
The module implements the following interfaces:
- modular.Module: Basic module lifecycle
- modular.Configurable: Configuration management
- modular.ServiceAware: Service dependency management
- modular.Startable: Startup logic
- modular.Stoppable: Shutdown logic
- modular.ObservableModule: Event observation and emission
func (*HTTPServerModule) Constructor ¶
func (m *HTTPServerModule) Constructor() modular.ModuleConstructor
Constructor returns a dependency injection function that initializes the module with required services
func (*HTTPServerModule) EmitEvent ¶ added in v0.2.0
func (m *HTTPServerModule) EmitEvent(ctx context.Context, event cloudevents.Event) error
EmitEvent implements the ObservableModule interface. This allows the httpserver module to emit events to registered observers.
func (*HTTPServerModule) GetRegisteredEventTypes ¶ added in v0.2.0
func (m *HTTPServerModule) GetRegisteredEventTypes() []string
GetRegisteredEventTypes implements the ObservableModule interface. Returns all event types that this httpserver module can emit.
func (*HTTPServerModule) Init ¶
func (m *HTTPServerModule) Init(app modular.Application) error
Init initializes the module with the provided application. This method loads the configuration, sets up the logger, and prepares the HTTP server for startup. It also attempts to resolve optional services like certificate management.
Initialization process:
- Load HTTP server configuration
- Set up logging
- Resolve optional certificate service for TLS
- Prepare server instance (actual startup happens in Start)
func (*HTTPServerModule) Name ¶
func (m *HTTPServerModule) Name() string
Name returns the name of the module. This name is used for dependency resolution and configuration section lookup.
func (*HTTPServerModule) ProvidesServices ¶
func (m *HTTPServerModule) ProvidesServices() []modular.ServiceProvider
ProvidesServices returns the services provided by this module
func (*HTTPServerModule) RegisterConfig ¶
func (m *HTTPServerModule) RegisterConfig(app modular.Application) error
RegisterConfig registers the module's configuration structure. The HTTP server module supports comprehensive configuration including:
- Server address and port settings
- Timeout configurations (read, write, idle, shutdown)
- TLS settings and certificate paths
- Security headers and CORS configuration
Default values are provided for common use cases, but can be overridden through configuration files or environment variables.
func (*HTTPServerModule) RegisterObservers ¶ added in v0.2.0
func (m *HTTPServerModule) RegisterObservers(subject modular.Subject) error
RegisterObservers implements the ObservableModule interface. This allows the httpserver module to register as an observer for events it's interested in.
func (*HTTPServerModule) RequiresServices ¶
func (m *HTTPServerModule) RequiresServices() []modular.ServiceDependency
RequiresServices returns the services required by this module
func (*HTTPServerModule) Start ¶
func (m *HTTPServerModule) Start(ctx context.Context) error
Start starts the HTTP server and begins accepting connections. This method configures the server with the loaded configuration, sets up TLS if enabled, and starts listening for HTTP requests.
The server startup process:
- Validate that a handler has been registered
- Create http.Server instance with configured timeouts
- Set up TLS certificates if HTTPS is enabled
- Start the server in a goroutine
- Handle graceful shutdown on context cancellation
The server will continue running until the context is cancelled or Stop() is called explicitly.
func (*HTTPServerModule) Stop ¶
func (m *HTTPServerModule) Stop(ctx context.Context) error
Stop stops the HTTP server gracefully. This method initiates a graceful shutdown of the HTTP server, allowing existing connections to finish processing before closing.
The shutdown process:
- Check if server is running
- Create shutdown context with configured timeout
- Call server.Shutdown() to stop accepting new connections
- Wait for existing connections to complete or timeout
- Mark server as stopped
If the shutdown timeout is exceeded, the server will be forcefully closed.
type TLSConfig ¶
type TLSConfig struct { // Enabled indicates if HTTPS should be used instead of HTTP Enabled bool `yaml:"enabled" json:"enabled" env:"TLS_ENABLED"` // CertFile is the path to the certificate file CertFile string `yaml:"cert_file" json:"cert_file" env:"TLS_CERT_FILE"` // KeyFile is the path to the private key file KeyFile string `yaml:"key_file" json:"key_file" env:"TLS_KEY_FILE"` // UseService indicates whether to use a certificate service instead of files // When true, the module will look for a CertificateService in its dependencies UseService bool `yaml:"use_service" json:"use_service" env:"TLS_USE_SERVICE"` // AutoGenerate indicates whether to automatically generate self-signed certificates // if no certificate service is provided and file paths are not specified AutoGenerate bool `yaml:"auto_generate" json:"auto_generate" env:"TLS_AUTO_GENERATE"` // Domains is a list of domain names to generate certificates for (when AutoGenerate is true) Domains []string `yaml:"domains" json:"domains" env:"TLS_DOMAINS"` }
TLSConfig holds the TLS configuration for HTTPS support