httpserver

package
v1.18.0 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2025 License: MIT Imports: 29 Imported by: 0

README

httpserver Package

httpserver/pool Subpackage

The httpserver/pool package provides a high-level abstraction for managing a pool of httpserver Package.
It allows you to configure, start, stop, and monitor multiple HTTP server instances as a unified group, with advanced filtering, merging, and handler management capabilities.

Features
  • Manage multiple HTTP server instances as a pool
  • Add, remove, and retrieve servers by bind address
  • Start, stop, and restart all servers in the pool with aggregated error handling
  • Filter and list servers by name, bind address, or expose address (with pattern or regex)
  • Merge pools and clone pool state
  • Register global handler functions for all servers
  • Monitor all servers and retrieve monitoring data
  • Thread-safe operations

Main Types & Interfaces
Pool Interface

The main interface for managing a pool of HTTP servers. Key methods include:

  • Start(ctx context.Context) error: Start all servers in the pool.
  • Stop(ctx context.Context) error: Stop all servers in the pool.
  • Restart(ctx context.Context) error: Restart all servers in the pool.
  • IsRunning() bool: Check if any server in the pool is running.
  • Uptime() time.Duration: Get the maximum uptime among all servers.
  • Handler(fct FuncHandler): Register a global handler function for all servers.
  • Monitor(vrs Version) ([]Monitor, error): Retrieve monitoring data for all servers.
  • Clone(ctx context.Context) Pool: Clone the pool (optionally with a new context).
  • Merge(p Pool, defLog FuncLog) error: Merge another pool into this one.
  • Manage and Filter interfaces for advanced management and filtering.
Manage Interface
  • Walk(fct FuncWalk) bool: Iterate over all servers.
  • StoreNew(cfg Config, defLog FuncLog) error: Add a new server from config.
  • Load(bindAddress string) Server: Retrieve a server by bind address.
  • Delete(bindAddress string): Remove a server by bind address.
  • MonitorNames() []string: List all monitor names.
Filter Interface
  • Has(bindAddress string) bool: Check if a server exists.
  • Len() int: Number of servers in the pool.
  • List(fieldFilter, fieldReturn FieldType, pattern, regex string) []string: List server fields matching criteria.
  • Filter(field FieldType, pattern, regex string) Pool: Filter servers by field and pattern/regex.
Config Type

A slice of server configuration objects. Provides helper methods to:

  • Set global handler, TLS, and context functions for all configs
  • Validate all configs
  • Instantiate a pool from the configs

Example Usage
import (
    "github.com/nabbar/golib/httpserver/pool"
    "github.com/nabbar/golib/httpserver"
    "github.com/nabbar/golib/logger"
    "context"
)

cfgs := pool.Config{
    /* ... fill with httpserver.Config objects ... */
}

err := cfgs.Validate()
if err != nil {
    // handle config validation error
}

p, err := cfgs.Pool(nil, nil, logger.Default)
if err != nil {
    // handle pool creation error
}

// Start all servers
if err := p.Start(context.Background()); err != nil {
    // handle start error
}

// Stop all servers
if err := p.Stop(context.Background()); err != nil {
    // handle stop error
}

Error Handling

All errors are wrapped with custom codes for diagnostics, such as:

  • ErrorParamEmpty
  • ErrorPoolAdd
  • ErrorPoolValidate
  • ErrorPoolStart
  • ErrorPoolStop
  • ErrorPoolRestart
  • ErrorPoolMonitor

Use err.Error() for user-friendly messages and check error codes for diagnostics.


Filtering and Listing

You can filter or list servers in the pool by name, bind address, or expose address, using exact match or regular expressions.

// List all bind addresses matching a pattern
binds := p.List(FieldBind, FieldBind, "127.0.0.1:8080", "")

// Filter pool by expose address regex
filtered := p.Filter(FieldExpose, "", "^/api")

Monitoring

Retrieve monitoring data for all servers in the pool:

monitors, err := p.Monitor(version)
if err != nil {
    // handle monitoring error
}

Notes
  • The pool is thread-safe and suitable for concurrent use.
  • All operations are designed for Go 1.18+.
  • Integrates with the logger, context, and monitor packages for advanced features.

Package httpserver

The httpserver package provides advanced abstractions for configuring, running, and monitoring HTTP servers in Go. It is designed for robust, concurrent, and production-grade server management, supporting TLS, custom handlers, logging, and health monitoring.


Key Features
  • Configurable HTTP/HTTPS servers with extensive options (timeouts, keep-alive, HTTP/2, TLS, etc.)
  • Handler registration for flexible routing and API management
  • Integrated logging and monitoring support
  • Thread-safe and suitable for concurrent use
  • Custom error codes for diagnostics and troubleshooting

Main Types
Config

Represents the configuration for a single HTTP server instance.
Key fields include:

  • Name: Unique server name (required)
  • Listen: Bind address (host:port or unix socket, required)
  • Expose: Public/external address (URL, required)
  • HandlerKey: Key to associate with a specific handler
  • Disabled: Enable/disable the server without removing its config
  • Monitor: Monitoring configuration
  • TLSMandatory: Require valid TLS configuration to start
  • TLS: TLS settings (can inherit defaults)
  • HTTP/2 and HTTP options: timeouts, max handlers, keep-alive, etc.
  • Logger: Logger configuration

Helper methods:

  • Clone(): Deep copy of the config
  • RegisterHandlerFunc(f): Register a handler function
  • SetDefaultTLS(f): Set default TLS provider
  • SetContext(f): Set parent context provider
  • Validate(): Validate config fields and constraints
  • Server(defLog): Instantiate a server from the config

Server Interface

Represents a running HTTP server instance.

  • Start(ctx) error: Start the server
  • Stop(ctx) error: Stop the server gracefully
  • Restart(ctx) error: Restart the server
  • IsRunning() bool: Check if the server is running
  • GetConfig() *Config: Get the current config
  • SetConfig(cfg, defLog) error: Update the config
  • Handler(f): Register handler function
  • Merge(srv, defLog) error: Merge another server's config
  • Monitor(version): Get monitoring data
  • MonitorName() string: Get monitor name
  • GetName() string: Get server name
  • GetBindable() string: Get bind address
  • GetExpose() string: Get expose address
  • IsDisable() bool: Check if server is disabled
  • IsTLS() bool: Check if TLS is enabled

Handler Management

Handlers are registered via a function returning a map of handler keys to http.Handler instances.
You can associate a server with a specific handler using the HandlerKey field.


Monitoring

Integrated with the monitoring system, each server can expose runtime, build, and health information.
Use Monitor(version) to retrieve monitoring data.


Error Handling

All errors are wrapped with custom codes for diagnostics, such as:

  • ErrorParamEmpty
  • ErrorHTTP2Configure
  • ErrorServerValidate
  • ErrorServerStart
  • ErrorPortUse

Use err.Error() for user-friendly messages and check error codes for diagnostics.


Example Usage
import (
    "github.com/nabbar/golib/httpserver"
    "github.com/nabbar/golib/logger"
    "context"
)

cfg := httpserver.Config{
    Name:   "api-server",
    Listen: "127.0.0.1:8080",
    Expose: "http://api.example.com:8080",
    // ... other fields
}
cfg.RegisterHandlerFunc(myHandlerFunc)
cfg.SetDefaultTLS(myTLSProvider)
cfg.SetContext(myContextProvider)

if err := cfg.Validate(); err != nil {
    // handle config error
}

srv, err := httpserver.New(cfg, logger.Default)
if err != nil {
    // handle server creation error
}

if err := srv.Start(context.Background()); err != nil {
    // handle start error
}

// ... later
if err := srv.Stop(context.Background()); err != nil {
    // handle stop error
}

Notes
  • The package is designed for Go 1.18+.
  • All operations are thread-safe.
  • Integrates with logger, context, and monitor packages for advanced features.
  • For advanced management of multiple servers, see the httpserver/pool package.

Documentation

Index

Constants

View Source
const (
	ErrorParamEmpty liberr.CodeError = iota + liberr.MinPkgHttpServer
	ErrorHTTP2Configure
	ErrorServerValidate
	ErrorServerStart
	ErrorPortUse
)
View Source
const (
	DefaultNameMonitor = "HTTP Server"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Config added in v1.10.0

type Config struct {

	// Name is the name of the current srv
	// the configuration allow multipke srv, which each one must be identify by a name
	// If not defined, will use the listen address
	Name string `mapstructure:"name" json:"name" yaml:"name" toml:"name" validate:"required"`

	// Listen is the local address (ip, hostname, unix socket, ...) with a port
	// The srv will bind with this address only and listen for the port defined
	Listen string `mapstructure:"listen" json:"listen" yaml:"listen" toml:"listen" validate:"required,hostname_port"`

	// Expose is the address use to call this srv. This can be allow to use a single fqdn to multiple srv"
	Expose string `mapstructure:"expose" json:"expose" yaml:"expose" toml:"expose" validate:"required,url"`

	// HandlerKey is an options to associate current srv with a specifc handler defined by the key
	// This key allow to defined multiple srv in only one config for different handler to start multiple api
	HandlerKey string `mapstructure:"handler_key" json:"handler_key" yaml:"handler_key" toml:"handler_key"`

	// Enabled allow to disable a srv without clean his configuration
	Disabled bool `mapstructure:"disabled" json:"disabled" yaml:"disabled" toml:"disabled"`

	// Monitor defined the monitoring options to monitor the status & metrics about the health of this srv
	Monitor moncfg.Config `mapstructure:"monitor" json:"monitor" yaml:"monitor" toml:"monitor"`

	// TLSMandatory is a flag to defined that TLS must be valid to start current srv.
	TLSMandatory bool `mapstructure:"tls_mandatory" json:"tls_mandatory" yaml:"tls_mandatory" toml:"tls_mandatory"`

	// TLS is the tls configuration for this srv.
	// To allow tls on this srv, at least the TLS Config option InheritDefault must be at true and the default TLS config must be set.
	// If you don't want any tls config, just omit or set an empty struct.
	TLS libtls.Config `mapstructure:"tls" json:"tls" yaml:"tls" toml:"tls"`

	// ReadTimeout is the maximum duration for reading the entire
	// request, including the body.
	//
	// Because ReadTimeout does not let Handlers make per-request
	// decisions on each request body's acceptable deadline or
	// upload rate, most users will prefer to use
	// ReadHeaderTimeout. It is valid to use them both.
	ReadTimeout libdur.Duration `mapstructure:"read_timeout" json:"read_timeout" yaml:"read_timeout" toml:"read_timeout"`

	// ReadHeaderTimeout is the amount of time allowed to read
	// request headers. The connection's read deadline is reset
	// after reading the headers and the Handler can decide what
	// is considered too slow for the body. If ReadHeaderTimeout
	// is zero, the value of ReadTimeout is used. If both are
	// zero, there is no timeout.
	ReadHeaderTimeout libdur.Duration `mapstructure:"read_header_timeout" json:"read_header_timeout" yaml:"read_header_timeout" toml:"read_header_timeout"`

	// WriteTimeout is the maximum duration before timing out
	// writes of the response. It is reset whenever a new
	// request's header is read. Like ReadTimeout, it does not
	// let Handlers make decisions on a per-request basis.
	WriteTimeout libdur.Duration `mapstructure:"write_timeout" json:"write_timeout" yaml:"write_timeout" toml:"write_timeout"`

	// MaxHeaderBytes controls the maximum number of bytes the
	// srv will read parsing the request header's keys and
	// values, including the request line. It does not limit the
	// size of the request body.
	// If zero, DefaultMaxHeaderBytes is used.
	MaxHeaderBytes int `mapstructure:"max_header_bytes" json:"max_header_bytes" yaml:"max_header_bytes" toml:"max_header_bytes"`

	// MaxHandlers limits the number of http.Handler ServeHTTP goroutines
	// which may run at a time over all connections.
	// Negative or zero no limit.
	MaxHandlers int `mapstructure:"max_handlers" json:"max_handlers" yaml:"max_handlers" toml:"max_handlers"`

	// MaxConcurrentStreams optionally specifies the number of
	// concurrent streams that each client may have open at a
	// time. This is unrelated to the number of http.Handler goroutines
	// which may be active globally, which is MaxHandlers.
	// If zero, MaxConcurrentStreams defaults to at least 100, per
	// the HTTP/2 spec's recommendations.
	MaxConcurrentStreams uint32 `` /* 127-byte string literal not displayed */

	// MaxReadFrameSize optionally specifies the largest frame
	// this srv is willing to read. A valid value is between
	// 16k and 16M, inclusive. If zero or otherwise invalid, a
	// default value is used.
	MaxReadFrameSize uint32 `mapstructure:"max_read_frame_size" json:"max_read_frame_size" yaml:"max_read_frame_size" toml:"max_read_frame_size"`

	// PermitProhibitedCipherSuites, if true, permits the use of
	// cipher suites prohibited by the HTTP/2 spec.
	PermitProhibitedCipherSuites bool `` /* 163-byte string literal not displayed */

	// IdleTimeout specifies how long until idle clients should be
	// closed with a GOAWAY frame. PING frames are not considered
	// activity for the purposes of IdleTimeout.
	IdleTimeout libdur.Duration `mapstructure:"idle_timeout" json:"idle_timeout" yaml:"idle_timeout" toml:"idle_timeout"`

	// MaxUploadBufferPerConnection is the size of the initial flow
	// control window for each connections. The HTTP/2 spec does not
	// allow this to be smaller than 65535 or larger than 2^32-1.
	// If the value is outside this range, a default value will be
	// used instead.
	MaxUploadBufferPerConnection int32 `` /* 167-byte string literal not displayed */

	// MaxUploadBufferPerStream is the size of the initial flow control
	// window for each stream. The HTTP/2 spec does not allow this to
	// be larger than 2^32-1. If the value is zero or larger than the
	// maximum, a default value will be used instead.
	MaxUploadBufferPerStream int32 `` /* 151-byte string literal not displayed */

	// DisableKeepAlive controls whether HTTP keep-alives are disabled.
	// By default, keep-alives are always enabled. Only very
	// resource-constrained environments or servers in the process of
	// shutting down should disable them.
	DisableKeepAlive bool `mapstructure:"disable_keep_alive" json:"disable_keep_alive" yaml:"disable_keep_alive" toml:"disable_keep_alive"`

	// Logger is used to define the logger options.
	Logger logcfg.Options `mapstructure:"logger" json:"logger" yaml:"logger" toml:"logger"`
	// contains filtered or unexported fields
}

nolint #maligned

func (*Config) CheckTLS added in v1.10.0

func (c *Config) CheckTLS() (libtls.TLSConfig, error)

func (*Config) Clone added in v1.10.0

func (c *Config) Clone() Config

func (*Config) GetExpose added in v1.10.0

func (c *Config) GetExpose() *url.URL

func (*Config) GetHandlerKey added in v1.10.0

func (c *Config) GetHandlerKey() string

func (*Config) GetListen added in v1.10.0

func (c *Config) GetListen() *url.URL

func (*Config) GetTLS added in v1.10.0

func (c *Config) GetTLS() (libtls.TLSConfig, error)

func (*Config) IsTLS added in v1.10.0

func (c *Config) IsTLS() bool

func (*Config) RegisterHandlerFunc added in v1.10.0

func (c *Config) RegisterHandlerFunc(hdl srvtps.FuncHandler)

func (*Config) Server added in v1.10.0

func (c *Config) Server(defLog liblog.FuncLog) (Server, error)

func (*Config) SetContext added in v1.10.0

func (c *Config) SetContext(f libctx.FuncContext)

func (*Config) SetDefaultTLS added in v1.10.0

func (c *Config) SetDefaultTLS(f libtls.FctTLSDefault)

func (*Config) Validate added in v1.10.0

func (c *Config) Validate() error

type Info added in v1.10.0

type Info interface {
	GetName() string
	GetBindable() string
	GetExpose() string

	IsDisable() bool
	IsTLS() bool
}

type Server added in v1.5.0

type Server interface {
	libsrv.Server

	Info

	Handler(h srvtps.FuncHandler)
	Merge(s Server, def liblog.FuncLog) error

	GetConfig() *Config
	SetConfig(cfg Config, defLog liblog.FuncLog) error

	Monitor(vrs libver.Version) (montps.Monitor, error)
	MonitorName() string
}

func New added in v1.10.0

func New(cfg Config, defLog liblog.FuncLog) (Server, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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