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) 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) RequiresServices() []modular.ServiceDependency
- func (m *HTTPServerModule) Start(ctx context.Context) error
- func (m *HTTPServerModule) Stop(ctx context.Context) error
- type TLSConfig
Constants ¶
const DefaultTimeoutSeconds = 15
DefaultTimeoutSeconds is the default timeout value in seconds
const ModuleName = "httpserver"
ModuleName is the name of this module for registration and dependency resolution.
Variables ¶
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") )
Error definitions for HTTP server operations.
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, in seconds. ReadTimeout int `yaml:"read_timeout" json:"read_timeout" env:"READ_TIMEOUT"` // WriteTimeout is the maximum duration before timing out writes of the response, // in seconds. WriteTimeout int `yaml:"write_timeout" json:"write_timeout" env:"WRITE_TIMEOUT"` // IdleTimeout is the maximum amount of time to wait for the next request, // in seconds. IdleTimeout int `yaml:"idle_timeout" json:"idle_timeout" env:"IDLE_TIMEOUT"` // ShutdownTimeout is the maximum amount of time to wait during graceful // shutdown, in seconds. ShutdownTimeout int `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) GetTimeout ¶
func (c *HTTPServerConfig) GetTimeout(seconds int) time.Duration
GetTimeout converts a timeout value from seconds to time.Duration. If seconds is 0, it returns the default timeout.
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
func (*HTTPServerModule) Constructor ¶
func (m *HTTPServerModule) Constructor() modular.ModuleConstructor
Constructor returns a dependency injection function that initializes the module with required services
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) 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