{"modulePath":"github.com/CrisisTextLine/modular/modules/httpserver","version":"v0.5.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package httpserver\n\nPackage httpserver provides an HTTP server module for the modular framework.\n\nPackage httpserver provides an HTTP server module for the modular framework.\n\nPackage 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.\n\nThe httpserver module features:\n\n  - HTTP and HTTPS server support\n  - Automatic TLS certificate generation and management\n  - Configurable timeouts and limits\n  - Graceful shutdown handling\n  - Handler registration and middleware support\n  - Health check endpoints\n  - Integration with Let's Encrypt for automatic certificates\n\nUsage:\n\n\tapp.RegisterModule(httpserver.NewModule())\n\nThe module registers an HTTP server service that can be used by other modules to register handlers, middleware, or access the underlying server instance.\n\nConfiguration:\n\n\tThe module requires an \"httpserver\" configuration section with server\n\tsettings including address, ports, TLS configuration, and timeout values.\n\n## Constants\n\n```go\nconst (\n\t// Server lifecycle events\n\tEventTypeServerStarted = \"com.modular.httpserver.server.started\"\n\tEventTypeServerStopped = \"com.modular.httpserver.server.stopped\"\n\n\t// Request handling events\n\tEventTypeRequestReceived = \"com.modular.httpserver.request.received\"\n\tEventTypeRequestHandled  = \"com.modular.httpserver.request.handled\"\n\n\t// TLS events\n\tEventTypeTLSEnabled    = \"com.modular.httpserver.tls.enabled\"\n\tEventTypeTLSConfigured = \"com.modular.httpserver.tls.configured\"\n\n\t// Configuration events\n\tEventTypeConfigLoaded = \"com.modular.httpserver.config.loaded\"\n)\n```\nEvent type constants for httpserver module events. Following CloudEvents specification reverse domain notation.\n\n```go\nconst DefaultTimeout = 15 * time.Second\n```\nDefaultTimeout is the default timeout value\n\n```go\nconst ModuleName = \"httpserver\"\n```\nModuleName is the name of this module for registration and dependency resolution.\n\n## Variables\n\n```go\nvar (\n\tErrInvalidPort           = errors.New(\"invalid port number\")\n\tErrTLSNoDomainsSpecified = errors.New(\"TLS auto-generation is enabled but no domains specified\")\n\tErrTLSNoCertificateFile  = errors.New(\"TLS is enabled but no certificate file specified\")\n\tErrTLSNoKeyFile          = errors.New(\"TLS is enabled but no key file specified\")\n)\n```\nStatic errors for configuration validation\n\n```go\nvar (\n\t// ErrServerNotStarted is returned when attempting to stop a server that hasn't been started.\n\tErrServerNotStarted = errors.New(\"server not started\")\n\n\t// ErrNoHandler is returned when no HTTP handler is available for the server.\n\tErrNoHandler = errors.New(\"no HTTP handler available\")\n\n\t// ErrRouterServiceNotHandler is returned when the router service doesn't implement http.Handler.\n\tErrRouterServiceNotHandler = errors.New(\"router service does not implement http.Handler\")\n\n\t// ErrServerStartTimeout is returned when the server fails to start within the timeout period.\n\tErrServerStartTimeout = errors.New(\"context cancelled while waiting for server to start\")\n)\n```\nError definitions for HTTP server operations.\n\n```go\nvar (\n\t// ErrNoSubjectForEventEmission is returned when trying to emit events without a subject\n\tErrNoSubjectForEventEmission = errors.New(\"no subject available for event emission\")\n)\n```\nError definitions\n\n## Functions\n\n```go\nfunc NewHTTPServerModule() modular.Module\n```\nNewHTTPServerModule creates a new instance of the HTTP server module. The returned module must be registered with the application before use.\n\nExample:\n\n\thttpModule := httpserver.NewHTTPServerModule()\n\tapp.RegisterModule(httpModule)\n\n## Types\n\n```go\ntype CertificateService interface {\n\t// GetCertificate returns a certificate for the given ClientHello\n\tGetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error)\n}\n```\nCertificateService defines the interface for a service that can provide TLS certificates\n\n```go\ntype HTTPServerConfig struct {\n\t// Host is the hostname or IP address to bind to.\n\tHost string `yaml:\"host\" json:\"host\" env:\"HOST\"`\n\n\t// Port is the port number to listen on.\n\tPort int `yaml:\"port\" json:\"port\" env:\"PORT\"`\n\n\t// ReadTimeout is the maximum duration for reading the entire request,\n\t// including the body.\n\tReadTimeout time.Duration `yaml:\"read_timeout\" json:\"read_timeout\" env:\"READ_TIMEOUT\"`\n\n\t// WriteTimeout is the maximum duration before timing out writes of the response.\n\tWriteTimeout time.Duration `yaml:\"write_timeout\" json:\"write_timeout\" env:\"WRITE_TIMEOUT\"`\n\n\t// IdleTimeout is the maximum amount of time to wait for the next request.\n\tIdleTimeout time.Duration `yaml:\"idle_timeout\" json:\"idle_timeout\" env:\"IDLE_TIMEOUT\"`\n\n\t// ShutdownTimeout is the maximum amount of time to wait during graceful\n\t// shutdown.\n\tShutdownTimeout time.Duration `yaml:\"shutdown_timeout\" json:\"shutdown_timeout\" env:\"SHUTDOWN_TIMEOUT\"`\n\n\t// MaxHeaderBytes limits the total size of HTTP request headers the server\n\t// will accept. Rejects oversized requests with 431 before parsing the body.\n\t// Go's built-in default is 1MB; a tighter limit reduces DoS surface.\n\t// Default: 32768 (32KB)\n\tMaxHeaderBytes int `yaml:\"max_header_bytes\" json:\"max_header_bytes\" env:\"MAX_HEADER_BYTES\"`\n\n\t// TLS configuration if HTTPS is enabled\n\tTLS *TLSConfig `yaml:\"tls\" json:\"tls\"`\n}\n```\nHTTPServerConfig defines the configuration for the HTTP server module.\n\n```go\nfunc (c *HTTPServerConfig) Validate() error\n```\nValidate checks if the configuration is valid and sets default values where appropriate.\n\n```go\ntype HTTPServerModule struct {\n\t// contains filtered or unexported fields\n}\n```\nHTTPServerModule 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.\n\nThe module manages:\n\n  - HTTP server lifecycle (start, stop, graceful shutdown)\n  - TLS certificate management and automatic generation\n  - Request routing and handler registration\n  - Server configuration and health monitoring\n  - Integration with certificate services for automatic HTTPS\n  - Event observation and emission for server operations\n\nThe module implements the following interfaces:\n\n  - modular.Module: Basic module lifecycle\n  - modular.Configurable: Configuration management\n  - modular.ServiceAware: Service dependency management\n  - modular.Startable: Startup logic\n  - modular.Stoppable: Shutdown logic\n  - modular.ObservableModule: Event observation and emission\n\n```go\nfunc (m *HTTPServerModule) Constructor() modular.ModuleConstructor\n```\nConstructor returns a dependency injection function that initializes the module with required services\n\n```go\nfunc (m *HTTPServerModule) EmitEvent(ctx context.Context, event cloudevents.Event) error\n```\nEmitEvent implements the ObservableModule interface. This allows the httpserver module to emit events to registered observers.\n\n```go\nfunc (m *HTTPServerModule) GetRegisteredEventTypes() []string\n```\nGetRegisteredEventTypes implements the ObservableModule interface. Returns all event types that this httpserver module can emit.\n\n```go\nfunc (m *HTTPServerModule) Init(app modular.Application) error\n```\nInit 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.\n\nInitialization process:\n\n 1. Load HTTP server configuration\n 2. Set up logging\n 3. Resolve optional certificate service for TLS\n 4. Prepare server instance (actual startup happens in Start)\n\n```go\nfunc (m *HTTPServerModule) Name() string\n```\nName returns the name of the module. This name is used for dependency resolution and configuration section lookup.\n\n```go\nfunc (m *HTTPServerModule) ProvidesServices() []modular.ServiceProvider\n```\nProvidesServices returns the services provided by this module\n\n```go\nfunc (m *HTTPServerModule) RegisterConfig(app modular.Application) error\n```\nRegisterConfig registers the module's configuration structure. The HTTP server module supports comprehensive configuration including:\n\n  - Server address and port settings\n  - Timeout configurations (read, write, idle, shutdown)\n  - TLS settings and certificate paths\n  - Security headers and CORS configuration\n\nDefault values are provided for common use cases, but can be overridden through configuration files or environment variables.\n\n```go\nfunc (m *HTTPServerModule) RegisterObservers(subject modular.Subject) error\n```\nRegisterObservers implements the ObservableModule interface. This allows the httpserver module to register as an observer for events it's interested in.\n\n```go\nfunc (m *HTTPServerModule) RequiresServices() []modular.ServiceDependency\n```\nRequiresServices returns the services required by this module\n\n```go\nfunc (m *HTTPServerModule) Start(ctx context.Context) error\n```\nStart 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.\n\nThe server startup process:\n\n 1. Validate that a handler has been registered\n 2. Create http.Server instance with configured timeouts\n 3. Set up TLS certificates if HTTPS is enabled\n 4. Start the server in a goroutine\n 5. Handle graceful shutdown on context cancellation\n\nThe server will continue running until the context is cancelled or Stop() is called explicitly.\n\n```go\nfunc (m *HTTPServerModule) Stop(ctx context.Context) error\n```\nStop stops the HTTP server gracefully. This method initiates a graceful shutdown of the HTTP server, allowing existing connections to finish processing before closing.\n\nThe shutdown process:\n\n 1. Check if server is running\n 2. Create shutdown context with configured timeout\n 3. Call server.Shutdown() to stop accepting new connections\n 4. Wait for existing connections to complete or timeout\n 5. Mark server as stopped\n\nIf the shutdown timeout is exceeded, the server will be forcefully closed.\n\n```go\ntype TLSConfig struct {\n\t// Enabled indicates if HTTPS should be used instead of HTTP\n\tEnabled bool `yaml:\"enabled\" json:\"enabled\" env:\"TLS_ENABLED\"`\n\n\t// CertFile is the path to the certificate file\n\tCertFile string `yaml:\"cert_file\" json:\"cert_file\" env:\"TLS_CERT_FILE\"`\n\n\t// KeyFile is the path to the private key file\n\tKeyFile string `yaml:\"key_file\" json:\"key_file\" env:\"TLS_KEY_FILE\"`\n\n\t// UseService indicates whether to use a certificate service instead of files\n\t// When true, the module will look for a CertificateService in its dependencies\n\tUseService bool `yaml:\"use_service\" json:\"use_service\" env:\"TLS_USE_SERVICE\"`\n\n\t// AutoGenerate indicates whether to automatically generate self-signed certificates\n\t// if no certificate service is provided and file paths are not specified\n\tAutoGenerate bool `yaml:\"auto_generate\" json:\"auto_generate\" env:\"TLS_AUTO_GENERATE\"`\n\n\t// Domains is a list of domain names to generate certificates for (when AutoGenerate is true)\n\tDomains []string `yaml:\"domains\" json:\"domains\" env:\"TLS_DOMAINS\"`\n}\n```\nTLSConfig holds the TLS configuration for HTTPS support\n\n","path":"github.com/CrisisTextLine/modular/modules/httpserver","name":"httpserver","synopsis":"Package httpserver provides an HTTP server module for the modular framework.","isRedistributable":true}
