http

package
v1.10.5 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package http provides an HTTP transport for the controls lifecycle controller, exposing health, readiness, and management endpoints for use with container orchestrators and load balancers.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultTLSConfig added in v1.9.5

func DefaultTLSConfig() *tls.Config

DefaultTLSConfig returns the hardened TLS configuration shared across HTTP and gRPC servers and the HTTP client. It enforces TLS 1.2 minimum with curated AEAD cipher suites and modern curve preferences.

Example
package main

import (
	"fmt"

	gtbhttp "github.com/phpboyscout/go-tool-base/pkg/http"
)

func main() {
	// DefaultTLSConfig returns the shared hardened TLS configuration
	// used by both HTTP and gRPC servers/clients.
	cfg := gtbhttp.DefaultTLSConfig()

	fmt.Println("Min TLS version:", cfg.MinVersion)
	fmt.Println("Cipher suites:", len(cfg.CipherSuites))
}
Output:
Min TLS version: 771
Cipher suites: 6

func HealthHandler

func HealthHandler(controller controls.HealthReporter) http.HandlerFunc

HealthHandler returns an http.HandlerFunc that responds with the controller's health report.

func LivenessHandler

func LivenessHandler(controller controls.HealthReporter) http.HandlerFunc

LivenessHandler returns an http.HandlerFunc that responds with the controller's liveness report.

func NewClient

func NewClient(opts ...ClientOption) *http.Client

NewClient returns an *http.Client with security-focused defaults: TLS 1.2 minimum, curated cipher suites, timeouts, connection limits, and redirect policy that rejects HTTPS-to-HTTP downgrades.

Example
package main

import (
	"time"

	gtbhttp "github.com/phpboyscout/go-tool-base/pkg/http"
)

func main() {
	// Create a hardened HTTP client with security defaults.
	client := gtbhttp.NewClient(
		gtbhttp.WithTimeout(10*time.Second),
		gtbhttp.WithMaxRedirects(5),
	)

	_ = client // Use like a standard *http.Client
}
Example (WithRetry)
package main

import (
	"time"

	gtbhttp "github.com/phpboyscout/go-tool-base/pkg/http"
)

func main() {
	// Create a client with automatic retry for transient failures.
	client := gtbhttp.NewClient(
		gtbhttp.WithTimeout(30*time.Second),
		gtbhttp.WithRetry(gtbhttp.RetryConfig{
			MaxRetries:     3,
			InitialBackoff: 500 * time.Millisecond,
			MaxBackoff:     30 * time.Second,
		}),
	)

	_ = client
}

func NewServer

func NewServer(ctx context.Context, cfg config.Containable, handler http.Handler) (*http.Server, error)

NewServer returns a new preconfigured http.Server.

func NewTransport

func NewTransport(tlsCfg *tls.Config) *http.Transport

NewTransport returns a preconfigured *http.Transport with security-focused defaults: curated TLS configuration, connection limits, and timeouts. If tlsCfg is nil, DefaultTLSConfig() is used.

func ReadinessHandler

func ReadinessHandler(controller controls.HealthReporter) http.HandlerFunc

ReadinessHandler returns an http.HandlerFunc that responds with the controller's readiness report.

func Register

func Register(ctx context.Context, id string, controller controls.Controllable, cfg config.Containable, logger logger.Logger, handler http.Handler, opts ...RegisterOption) (*http.Server, error)

Register creates a new HTTP server and registers it with the controller under the given id.

func ResolveTLSConfig added in v1.9.5

func ResolveTLSConfig(cfg config.Containable, transportPrefix string) (bool, string, string)

ResolveTLSConfig reads TLS configuration with cascading precedence: transport-specific prefix (e.g. "server.http.tls" or "server.grpc.tls") falls back to the shared "server.tls" prefix. This allows a single cert to be used by both HTTP and gRPC, with per-transport overrides when needed.

Returns (enabled, certPath, keyPath).

func Start

func Start(cfg config.Containable, logger logger.Logger, srv *http.Server) controls.StartFunc

Start returns a curried function suitable for use with the controls package.

func Status

func Status(srv *http.Server) controls.StatusFunc

Status returns a curried function suitable for use with the controls package.

func Stop

func Stop(logger logger.Logger, srv *http.Server) controls.StopFunc

Stop returns a curried function suitable for use with the controls package.

Types

type Chain added in v1.8.0

type Chain struct {
	// contains filtered or unexported fields
}

Chain composes zero or more Middleware into a single Middleware. Middleware is applied left-to-right: the first middleware in the list is the outermost wrapper (first to see the request, last to see the response).

chain := NewChain(recovery, logging, auth)
handler := chain.Then(mux)

func NewChain added in v1.8.0

func NewChain(middlewares ...Middleware) Chain

NewChain creates a new middleware chain from the given middleware functions. Nil entries are silently skipped.

func (Chain) Append added in v1.8.0

func (c Chain) Append(middlewares ...Middleware) Chain

Append returns a new Chain with additional middleware appended. The original chain is not modified. Nil entries are silently skipped.

func (Chain) Extend added in v1.8.0

func (c Chain) Extend(other Chain) Chain

Extend returns a new Chain that applies c's middleware first, then other's.

func (Chain) Then added in v1.8.0

func (c Chain) Then(handler http.Handler) http.Handler

Then applies the middleware chain to the given handler and returns the resulting http.Handler.

If handler is nil, http.DefaultServeMux is used.

func (Chain) ThenFunc added in v1.8.0

func (c Chain) ThenFunc(fn http.HandlerFunc) http.Handler

ThenFunc is a convenience for Then(http.HandlerFunc(fn)).

type ClientChain added in v1.10.0

type ClientChain struct {
	// contains filtered or unexported fields
}

ClientChain composes ClientMiddleware in order. Immutable — Append returns a new chain.

func NewClientChain added in v1.10.0

func NewClientChain(middlewares ...ClientMiddleware) ClientChain

NewClientChain creates a ClientChain from the given middleware.

Example
package main

import (
	"os"
	"time"

	gtbhttp "github.com/phpboyscout/go-tool-base/pkg/http"
	"github.com/phpboyscout/go-tool-base/pkg/logger"
)

func main() {
	// Compose client middleware for auth, logging, and rate limiting.
	chain := gtbhttp.NewClientChain(
		gtbhttp.WithRequestLogging(logger.NewNoop()),
		gtbhttp.WithBearerToken(os.Getenv("API_TOKEN")),
		gtbhttp.WithRateLimit(10), // 10 requests per second
	)

	client := gtbhttp.NewClient(
		gtbhttp.WithTimeout(30*time.Second),
		gtbhttp.WithClientMiddleware(chain),
	)

	_ = client // Use like a standard *http.Client
}

func (ClientChain) Append added in v1.10.0

func (c ClientChain) Append(middlewares ...ClientMiddleware) ClientChain

Append returns a new chain with additional middleware appended.

func (ClientChain) Then added in v1.10.0

Then applies the middleware chain to the given RoundTripper and returns the wrapped result.

type ClientMiddleware added in v1.10.0

type ClientMiddleware func(next http.RoundTripper) http.RoundTripper

ClientMiddleware wraps an http.RoundTripper with additional behaviour. The first middleware in a chain is the outermost wrapper — it executes first on the request and last on the response.

func WithBasicAuth added in v1.10.0

func WithBasicAuth(username, password string) ClientMiddleware

WithBasicAuth returns middleware that injects an Authorization: Basic header on every request.

func WithBearerToken added in v1.10.0

func WithBearerToken(token string) ClientMiddleware

WithBearerToken returns middleware that injects an Authorization: Bearer header on every request.

func WithRateLimit added in v1.10.0

func WithRateLimit(requestsPerSecond float64) ClientMiddleware

WithRateLimit returns middleware that limits outbound requests to the specified rate using a token bucket algorithm. Blocks until a token is available or the request context is cancelled.

func WithRequestLogging added in v1.10.0

func WithRequestLogging(log logger.Logger) ClientMiddleware

WithRequestLogging returns middleware that logs each outbound request and response at debug level. Logs method, URL, status code, and duration. Headers and body are NOT logged for security.

type ClientOption

type ClientOption func(*clientConfig)

ClientOption configures the secure HTTP client.

func WithClientMiddleware added in v1.10.0

func WithClientMiddleware(chain ClientChain) ClientOption

WithClientMiddleware applies a middleware chain to the client's transport. The chain wraps the transport after retry (if configured) so that retry operates on the raw transport, not on logged/authed requests.

func WithMaxRedirects

func WithMaxRedirects(n int) ClientOption

WithMaxRedirects sets the maximum number of redirects to follow. Default: 10. Set to 0 to disable redirect following entirely.

func WithRetry added in v1.8.0

func WithRetry(cfg RetryConfig) ClientOption

WithRetry enables automatic retry with exponential backoff for transient failures.

func WithTLSConfig

func WithTLSConfig(cfg *tls.Config) ClientOption

WithTLSConfig overrides the default TLS configuration. The caller is responsible for ensuring the provided config meets security requirements.

func WithTimeout

func WithTimeout(d time.Duration) ClientOption

WithTimeout sets the overall request timeout. Default: 30s.

func WithTransport

func WithTransport(rt http.RoundTripper) ClientOption

WithTransport overrides the entire HTTP transport. When set, transport-level options (TLS config, connection limits) are ignored.

type LogFormat added in v1.8.0

type LogFormat int

LogFormat controls the output format of the logging middleware.

const (
	// FormatStructured emits structured key-value fields via logger.Logger.
	FormatStructured LogFormat = iota

	// FormatCommon emits NCSA Common Log Format (CLF).
	FormatCommon

	// FormatCombined emits NCSA Combined Log Format (CLF + Referer + User-Agent).
	FormatCombined

	// FormatJSON emits a single JSON object per request.
	FormatJSON
)

type LoggingOption added in v1.8.0

type LoggingOption func(*loggingConfig)

LoggingOption configures transport logging behaviour.

func WithFormat added in v1.8.0

func WithFormat(format LogFormat) LoggingOption

WithFormat sets the log output format. Defaults to FormatStructured.

func WithHeaderFields added in v1.8.0

func WithHeaderFields(headers ...string) LoggingOption

WithHeaderFields logs the specified request header values as fields. Header names are normalised to lowercase. Values are truncated to 256 bytes.

func WithLogLevel added in v1.8.0

func WithLogLevel(level logger.Level) LoggingOption

WithLogLevel sets the log level for successful requests. Defaults to logger.InfoLevel. Errors always log at logger.ErrorLevel.

func WithPathFilter added in v1.8.0

func WithPathFilter(paths ...string) LoggingOption

WithPathFilter excludes requests matching the given paths from logging.

func WithoutLatency added in v1.8.0

func WithoutLatency() LoggingOption

WithoutLatency disables the "latency" field.

func WithoutUserAgent added in v1.8.0

func WithoutUserAgent() LoggingOption

WithoutUserAgent disables the "user_agent" field.

type Middleware added in v1.8.0

type Middleware func(http.Handler) http.Handler

Middleware is the standard Go HTTP middleware signature.

func LoggingMiddleware added in v1.8.0

func LoggingMiddleware(l logger.Logger, opts ...LoggingOption) Middleware

LoggingMiddleware returns an HTTP Middleware that logs each completed request.

type RegisterOption added in v1.8.0

type RegisterOption func(*registerConfig)

RegisterOption configures optional behaviour for HTTP server registration.

func WithMiddleware added in v1.8.0

func WithMiddleware(chain Chain) RegisterOption

WithMiddleware sets the middleware chain applied to the handler before it is passed to the HTTP server. Health endpoints (/healthz, /livez, /readyz) are mounted outside the chain and are never affected by middleware.

type RetryConfig added in v1.8.0

type RetryConfig struct {
	// MaxRetries is the maximum number of retry attempts. Zero means no retries.
	MaxRetries int
	// InitialBackoff is the base delay before the first retry. Default: 500ms.
	InitialBackoff time.Duration
	// MaxBackoff caps the computed delay. Default: 30s.
	MaxBackoff time.Duration
	// RetryableStatusCodes defines which HTTP status codes trigger a retry.
	// Default: []int{429, 502, 503, 504}.
	RetryableStatusCodes []int
	// ShouldRetry is an optional custom predicate. When set, it replaces the
	// default status-code and network-error checks. The attempt count (0-based)
	// and either the response or the transport error are provided.
	ShouldRetry func(attempt int, resp *http.Response, err error) bool
}

RetryConfig configures the retry behaviour of the HTTP client.

func DefaultRetryConfig added in v1.8.0

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns a RetryConfig suitable for most use cases.

Jump to

Keyboard shortcuts

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