httpserver

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2025 License: MIT Imports: 17 Imported by: 0

README

HTTP Server Module

Go Reference

This module provides HTTP/HTTPS server capabilities for the modular framework. It handles listening on a specified port, TLS configuration, and server timeouts.

Features

  • HTTP and HTTPS support
  • Configurable host and port bindings
  • Customizable timeouts
  • Graceful shutdown
  • TLS support

Configuration

The module can be configured using YAML, JSON, or environment variables:

httpserver:
  host: "0.0.0.0"     # Host to bind to (default: 0.0.0.0)
  port: 8080          # Port to listen on (default: 8080)
  read_timeout: 15    # Maximum duration for reading requests (seconds)
  write_timeout: 15   # Maximum duration for writing responses (seconds)
  idle_timeout: 60    # Maximum time to wait for the next request (seconds)
  shutdown_timeout: 30 # Maximum time for graceful shutdown (seconds)
  tls:
    enabled: false    # Whether TLS is enabled
    cert_file: ""     # Path to TLS certificate file
    key_file: ""      # Path to TLS private key file

Usage

This module works with other modules in the application:

  1. It depends on a router module (like chimux) which provides the HTTP handler.
  2. The HTTP server listens on the configured port and passes incoming requests to the router.
  3. The router then directs requests to appropriate handlers, such as the reverseproxy module.
Integration Example
package main

import (
	"github.com/CrisisTextLine/modular"
	"github.com/CrisisTextLine/modular/modules/chimux"
	"github.com/CrisisTextLine/modular/modules/httpserver"
	"github.com/CrisisTextLine/modular/modules/reverseproxy"
)

func main() {
	app := modular.NewApplication()
	
	// Register modules in the appropriate order
	app.RegisterModule(chimux.NewChiMuxModule())
	app.RegisterModule(reverseproxy.NewReverseProxyModule())
	app.RegisterModule(httpserver.NewHTTPServerModule())
	
	// Initialize and run the application
	if err := app.Run(); err != nil {
		panic(err)
	}
}

Architecture

The HTTP server module integrates with the modular framework as follows:

┌────────────────────┐     ┌────────────────────┐     ┌────────────────────┐
│                    │     │                    │     │                    │
│    HTTP Server     │────▶│    Router (Chi)    │────▶│   Reverse Proxy    │
│                    │     │                    │     │                    │
└────────────────────┘     └────────────────────┘     └────────────────────┘
   Listens on port         Routes based on URL        Proxies to backends

Dependencies

  • Requires a module that provides the router service implementing http.Handler
  • Typically used with the chimux module

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

View Source
const DefaultTimeoutSeconds = 15

DefaultTimeoutSeconds is the default timeout value in seconds

View Source
const ModuleName = "httpserver"

ModuleName is the name of this module for registration and dependency resolution.

Variables

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

func NewHTTPServerModule() modular.Module

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

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:

  1. Load HTTP server configuration
  2. Set up logging
  3. Resolve optional certificate service for TLS
  4. 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:

  1. Validate that a handler has been registered
  2. Create http.Server instance with configured timeouts
  3. Set up TLS certificates if HTTPS is enabled
  4. Start the server in a goroutine
  5. 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:

  1. Check if server is running
  2. Create shutdown context with configured timeout
  3. Call server.Shutdown() to stop accepting new connections
  4. Wait for existing connections to complete or timeout
  5. 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

Jump to

Keyboard shortcuts

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