httpserver

package
v0.0.0-...-4ceac3e Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2026 License: MIT Imports: 6 Imported by: 0

README

HTTP Transport Module

The HTTP TLS Module is intended for use by http based transport protocols. The module server includes support for common middleware such as cors, logging, recovery, compression. authentication and file server and provides callback hooks for logging and authentication interaction.

The server provides two convenient routers for adding endpoints, a secured router which requires authentication and an unsecured router.

The client contains the boilerplate for establishing TLS connections including CA certificate, authorization bearer token, cid, other headers, URI parameters and request timeout.

Configuration

To operate a TLS server this requires:

  • CA public certificate
  • TLS certificate (x509 certificate + private key) signed by a CA

CORS configuration is only needed when serving web browsers. If enabled:

  • CORS requests from 127.0.0.1 or localhost are always allowed. Intended for testing.
  • CORS requests from https://{server-addr}/ same origin is allowed
  • CORS requests from configured origins are allowed. Anything else is blocked.
  • Default headers: "Origin", "Accept", "Content-Type", "Authorization", "Headers"
  • Default methods: GET, PUT, POST, PATCH, DELETE, OPTIONS

Callback hooks:

  • config.Authenticate is a function to authenticate incoming requests for the protected routes. This is disabled by default so it must be set by the application in order to protect this route.
  • config.Logger is the handler for logging http requests. Default is the chi middleware.Logger.

Other configuration:

  • Address: default "" (any)
  • Port: default 8444
  • Logger: defaults to chi's logger
  • Recovery: enabled
  • Compression: 5, gzip, ... or brotli
  • StripSlashes: disabled

Usage

There are two ways to create a HttpsBase module instance: using the pipeline factory or manually.

Pipeline Factory

This module is intended for use with http based transport protocols such as WoT HTTP-Basic, Websocket, the HiveOT SSE subprotocols and the authentication service for handling login and token refresh.

When using the pipeline factory, the server is automatically instantiated when a http based message transport is needed.

Manual Setup

Manual HTTPS Server creation requires configuration with a listening port, server TLS certificate, CA certificate, and authenticator.

The certificates can be loaded manually or obtained from the certs module. The authenticator can be supplied manually or obtained from the authn module.

See NewHttpsBaseOptions for defaults.

 config := NewHttpsBaseOptions()
 config.CaCert = certsModule.GetCACert(),
 config.ServerCert = certsModule.GetDefaultServerCert(),
 config.Authenticator = authnModule.GetAuthenticator()
 module := NewHttpsBaseModule(config)
 err := module.Start()
 prouter := module.GetPublicRouter()
 srouter := module.GetSecuredRouter()

The routers can directly be used in the transport modules.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type HttpServerConfig

type HttpServerConfig struct {
	Address    string            `yaml:"address,omitempty"`
	Port       int               `yaml:"port,omitempty"`
	CaCert     *x509.Certificate `yaml:"-"`
	ServerCert *tls.Certificate  `yaml:"-"`

	// NoTLS disables the use of TLS. For testing obviously
	NoTLS bool `yaml:"noTLS,omitempty"`

	// AuthenticateHandler authenticate requests on the protected route.
	//
	// This is optional for using a custom authentication mechanism.
	// This defaults to an internal function that takes the bearer token
	// from the request and passes it to the ValidateToken from this configuration.
	//
	// Note that ValidateToken is required when using the default handler.
	//
	// Other authentication schemes can be implemented by providing your own
	// function here.
	AuthenticateHandler func(req *http.Request) (clientID string, role string, err error) `yaml:"-"`

	// CorsEnabled enables the use of net/http CORS and adds the relevant CORS
	// headers to allow browser cross-domain calls in scripts.
	//
	// Use CorsAllowedOrigins to set the additional allowed cross-domains requests.
	//
	// This manages which origins are allowed for example to retrieve data
	// from a different API, as is typical in an IoT environment.
	// Enable this when serving a web site for browsers and allow cross-domain access to
	// specific endpoints on another server.
	// Typically not needed in an IoT setup, unless serving web pages.
	CorsEnabled bool `yaml:"corsEnabled"`

	// When CORS is enabled, allow these domain names. (eg https://*.otherdomain.com)
	CorsAllowedOrigins []string `yaml:"corsAllowedOrigins"`

	// Enable gzip compression
	GZipEnabled bool `yaml:"gzipEnabled,omitempty"`

	// GZip compression level when enabled -1..9
	GZipLevel int `yaml:"gzipLevel"`

	// GZip compression content types
	GZipContentTypes []string `yaml:"gzipContentTypes,omitempty"`

	// Optional middleware logger
	// Defaults to chi middelware.Logger
	// alternative: https://github.com/goware/httplog
	Logger func(http.Handler) http.Handler `yaml:"-"`

	// Recover from panics and return 500 error
	// Defaults to chi middleware.Recoverer
	// Set to nil to disable recovery and crash on panic.
	Recoverer func(http.Handler) http.Handler `yaml:"-"`

	// DisableStStripSlashesEnabledripSlashes remove trailing '/' in path
	StripSlashesEnabled bool `yaml:"stripSlashesEnabled,omitempty"`

	// Bearer token authenticator for protected routes.
	// The token validator MUST check for a valid clientID and token validity.
	//
	// This defaults to blocking all requests.
	//
	// Set to a custom function to perform actual token authentication.
	// any transports.IAuthenticator implementation can provide a ValidateToken function.
	ValidateTokenHandler transports.ValidateTokenHandler
}

Configuration options for the https server

func NewHttpServerConfig

func NewHttpServerConfig(
	addr string, port int, serverCert *tls.Certificate, caCert *x509.Certificate,
	validateToken transports.ValidateTokenHandler) *HttpServerConfig

NewHttpServerConfig creates options with defaults

addr is optional address, default is outbound address
port is optional listening port, 0 for default 8444
serverCert TLS certificate signed by the CA
caCert x509 CA certificate
validateToken is the required handler for authenticating protected routes

Directories

Path Synopsis
Package tlsclient with a TLS client helper supporting certificate, JWT or Basic authentication
Package tlsclient with a TLS client helper supporting certificate, JWT or Basic authentication

Jump to

Keyboard shortcuts

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