httpserver

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2025 License: MIT Imports: 17 Imported by: 1

README

HTTP Server Module

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/GoCodeAlone/modular"
	"github.com/GoCodeAlone/modular/modules/chimux"
	"github.com/GoCodeAlone/modular/modules/httpserver"
	"github.com/GoCodeAlone/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.

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

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
	ErrNoHandler = errors.New("no HTTP handler available")
)

Error definitions

Functions

func NewHTTPServerModule

func NewHTTPServerModule() modular.Module

NewHTTPServerModule creates a new instance of the HTTP server module

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"`

	// Port is the port number to listen on.
	Port int `yaml:"port" json:"port"`

	// ReadTimeout is the maximum duration for reading the entire request,
	// including the body, in seconds.
	ReadTimeout int `yaml:"read_timeout" json:"read_timeout"`

	// WriteTimeout is the maximum duration before timing out writes of the response,
	// in seconds.
	WriteTimeout int `yaml:"write_timeout" json:"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"`

	// ShutdownTimeout is the maximum amount of time to wait during graceful
	// shutdown, in seconds.
	ShutdownTimeout int `yaml:"shutdown_timeout" json:"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

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

func (*HTTPServerModule) Name

func (m *HTTPServerModule) Name() string

Name returns the name of the module

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

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

func (*HTTPServerModule) Stop

func (m *HTTPServerModule) Stop(ctx context.Context) error

Stop stops the HTTP server

type TLSConfig

type TLSConfig struct {
	// Enabled indicates if HTTPS should be used instead of HTTP
	Enabled bool `yaml:"enabled" json:"enabled"`

	// CertFile is the path to the certificate file
	CertFile string `yaml:"cert_file" json:"cert_file"`

	// KeyFile is the path to the private key file
	KeyFile string `yaml:"key_file" json:"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"`

	// 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"`

	// Domains is a list of domain names to generate certificates for (when AutoGenerate is true)
	Domains []string `yaml:"domains" json:"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