settings

package module
v0.0.5 Latest Latest
Warning

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

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

README

Go HTTP Settings

This project provides a configurable HTTP server in Go. It is designed to be a flexible and extensible foundation for building web services, with a focus on security and production-readiness. The server is configured through a YAML file, and its functionality is extended through a series of middlewares.

Features

The server supports the following features, each of which can be configured through the settings file:

  • Server: Basic server settings like host and port.
  • SSL: Enable and configure SSL/TLS.
  • Authentication: JWT-based authentication.
  • Rate Limiting: Limit the number of requests per client.
  • Root Settings: Prevent IP address spoofing by removing Forwarded and X-Forwarded-For headers. This should only be used at the edge of your network.
  • Tracing: Add a trace ID to each request.
  • Gzip: Compress responses using gzip.
  • Headers: Add custom headers to responses.
  • Logging: Log requests and responses.

Configuration

The server is configured using a YAML or JSON file. The configuration is composed of different sections, each corresponding to a feature.

Example Configuration:

# server.yaml

# Server settings
read-timeout: 10s
read-header-timeout: 1s
write-timeout: 10s
idle-timeout: 10s
close-timeout: 10s
max-header-bytes: 16384

# SSL settings
ssl:
  example.com:
    - cert: "server.crt"
      key: "server.key"

# Authentication settings
auth:
  openid-providers:
    - name: exampmle
      issuer: https://example.com
      client-id: audience
      jwks-uri: "https://example.com/oauth2/keys"

# Rate limiter settings
limiter:
  rate: 10.0
  burst: 200
  size: 1024

# Root settings
root: true

# Trace settings
trace: true

# Gzip settings
gzip:
  level: 5

# Headers settings
headers:
  "X-Content-Type-Options": "nosniff"

# Log settings
log:
  status: true
  body: true
  body-max-size: 1024

Usage

To build and run the test echo server:

go build -o echo ./cmd/echo
./echo -config testing/echo.yaml

Middleware Order

The server uses a middleware chain to process requests. The middlewares are applied in the following order:

  1. Log: The log middleware is first (and last) to calculate the request duration.
  2. Trace: The trace middleware is second to ensure all responses have a trace ID.
  3. Limiter: The rate limiter is applied to incoming requests.
  4. Auth: The authentication middleware is applied after the rate limiter.
  5. Root: The root middleware is applied next.
  6. Gzip: The gzip middleware compresses the response.
  7. Headers: The headers middleware adds custom headers to the response.
Request -> Log -> Trace -> Limiter -> Auth -> Root -> [Your Handler] -> Gzip -> Headers -> Log -> Response

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func TraceXRequestID

func TraceXRequestID() string

TraceXRequestID provides a default function to provide values for the X-Request-Id header.

Types

type Auth

type Auth struct {
	OpenIDProviders []OpenIDProvider `yaml:"openid-providers" json:"openid-providers"`
}

Auth contains the authentication settings.

type AuthSettings

type AuthSettings struct {
	Auth *Auth `yaml:"auth" json:"auth"`
	// contains filtered or unexported fields
}

AuthSettings checks that the incoming HTTP requests are properly authenticated by one of the provided OpenID, Scope or TestID providers.

func (*AuthSettings) Initialize

func (as *AuthSettings) Initialize(ctx context.Context) error

Initialize initializes AuthSettings. Only needed after (YAML or JSON) unmarshaling an AuthSettings.

func (AuthSettings) Middleware

func (as AuthSettings) Middleware(h http.Handler) http.Handler

Middleware returns a new http.Handler that applies the authentication middleware.

type Auto

type Auto struct {
	Provider  string   `yaml:"provider"  json:"provider"`
	CertsDir  string   `yaml:"certs-dir" json:"certs-dir"`
	Email     string   `yaml:"email"     json:"email"`
	HostNames []string `yaml:"hosts"     json:"hosts"`
}

Auto contains the settings for automatic SSL certificate generation.

type GZip

type GZip struct {
	Level   *int `yaml:"level"    json:"level"`
	MinSize *int `yaml:"min-size" json:"min-size"`
}

GZip contains the gzip settings.

type GZipSettings

type GZipSettings struct {
	GZip *GZip `yaml:"gzip" json:"gzip"`
}

GZipSettings allows the response body to be compressed (with gzip). The Level specifies the level at which gzip should compress the data: 0 is no compression, 1 is minimal compression, 9 is maximal compression, and -1 or 6 are recommended compression. The MinSize specifies the minimal size in bytes of the response body before compression is used. If no MinSize is specified, a default value of 1400 bytes is used.

func (*GZipSettings) Initialize

func (gs *GZipSettings) Initialize() error

Initialize checks if the settings are valid.

func (*GZipSettings) Middleware

func (gs *GZipSettings) Middleware(h http.Handler) http.Handler

Middleware returns a new http.Handler that applies the gzip middleware.

type HeadersSettings

type HeadersSettings struct {
	Headers map[string]string `yaml:"headers" json:"headers"`
}

HeadersSettings allows for setting extra headers in the response. This is useful for setting default security headers.

func (*HeadersSettings) Initialize

func (hs *HeadersSettings) Initialize() error

Initialize checks if the settings are valid.

func (HeadersSettings) Middleware

func (hs HeadersSettings) Middleware(h http.Handler) http.Handler

Middleware returns a new http.Handler that adds the configured headers to the response.

type Host

type Host struct {
	CertFileName string `yaml:"cert" json:"cert"`
	KeyFileName  string `yaml:"key"  json:"key"`
}

Host contains the certificate and key file for a specific host.

type Limiter

type Limiter struct {
	Rate      float64 `yaml:"rate"       json:"rate"`
	Burst     int     `yaml:"burst"      json:"burst"`
	CacheSize int     `yaml:"cache-size" json:"cache-size"`
}

Limiter contains the rate and burst for the rate limiter.

type LimiterSettings

type LimiterSettings struct {
	Limiter *Limiter `yaml:"limit" json:"limit"`
}

LimiterSettings allows for limiting the number of requests per IP address. This is useful to protect against Denial of Service attacks.

func (*LimiterSettings) Initialize

func (ls *LimiterSettings) Initialize() error

Initialize checks if the settings are valid.

func (LimiterSettings) Middleware

func (ls LimiterSettings) Middleware(h http.Handler) http.Handler

Middleware returns a new http.Handler that applies the rate limiting middleware.

type Log

type Log struct {
	Status      bool `yaml:"status" json:"status"`
	Body        bool `yaml:"body"   json:"body"`
	BodyMaxSize int  `yaml:"body-max-size" json:"body-max-size"`
}

Log contains the log settings.

type LogSettings

type LogSettings struct {
	Log *Log `yaml:"log" json:"log"`
	// contains filtered or unexported fields
}

LogSettings specifies that logging of each incoming HTTP request is wanted. The log will optionally contain the HTTP request body and the HTTP response status.

func (*LogSettings) Initialize

func (ls *LogSettings) Initialize() error

Initialize checks if the settings are valid.

func (LogSettings) Middleware

func (ls LogSettings) Middleware(h http.Handler) http.Handler

Middleware returns a new http.Handler that logs requests.

func (*LogSettings) SetLogger

func (ls *LogSettings) SetLogger(logger *log.Logger)

SetLogger allows you to specify a non-default logger.

type OpenIDProvider

type OpenIDProvider struct {
	Name         string `yaml:"name"           json:"name"`
	Issuer       string `yaml:"issuer"         json:"issuer"`
	ClientID     string `yaml:"client-id"      json:"client-id"`
	JWKsURI      string `yaml:"jwks-uri"       json:"jwks-uri"`
	WellKnownURL string `yaml:"well-known-url" json:"well-known-url"`
}

OpenIDProvider contains the settings for an OpenID provider.

func (OpenIDProvider) New

New creates a new authorization.Provider from the OpenIDProvider settings.

type RootSettings

type RootSettings struct {
	Root *bool `yaml:"root" json:"root"`
}

RootSettings prevents malicious users from using headers to manipulate HTTP responses to include bad IP addresses. It is important to only enable this at the root reverse proxy.

func (*RootSettings) Initialize

func (rs *RootSettings) Initialize() error

func (RootSettings) Middleware

func (rs RootSettings) Middleware(h http.Handler) http.Handler

Middleware removes the "Forwarded" and "X-Forwarded-For" headers from the request.

type SSL

type SSL struct {
	Auto       *Auto           `yaml:"auto"  json:"auto"`
	HostByName map[string]Host `yaml:"hosts" json:"hosts"`
}

SSL contains the SSL settings.

type SSLSettings

type SSLSettings struct {
	SSL *SSL `yaml:"ssl" json:"ssl"`
	// contains filtered or unexported fields
}

SSLSettings specifies whether an HTTP server should use encryption through SSL. You can specify the certificate and key file, or you can specify the SSL certificate authority for automatic updating certificates.

func (*SSLSettings) Initialize

func (ss *SSLSettings) Initialize() error

Initialize checks if the settings are valid.

func (*SSLSettings) TLSConfig

func (ss *SSLSettings) TLSConfig() *tls.Config

TLSConfig returns the tls.Config for the server.

type ServerSettings

type ServerSettings struct {
	ReadTimeout       time.Duration `yaml:"read-timeout"        json:"read-timeout,format:units"`
	ReadHeaderTimeout time.Duration `yaml:"read-header-timeout" json:"read-header-timeout,format:units"`
	WriteTimeout      time.Duration `yaml:"write-timeout"       json:"write-timeout,format:units"`
	IdleTimeout       time.Duration `yaml:"idle-timeout"        json:"idle-timeout,format:units"`
	CloseTimeout      time.Duration `yaml:"close-timeout"       json:"close-timeout,format:units"`
	MaxHeaderBytes    int           `yaml:"max-header-bytes"    json:"max-header-bytes"`
}

ServerSettings contains several request level settings. It is a good security practice to provide these values to minimize the effect of Denial of Service attacks.

func (*ServerSettings) Initialize

func (ss *ServerSettings) Initialize() error

Initialize checks if the settings are valid.

type Settings

type Settings struct {
	// server creation
	ServerSettings `yaml:",inline" json:",inline"`
	SSLSettings    `yaml:",inline" json:",inline"`
	// in
	AuthSettings    `yaml:",inline" json:",inline"`
	LimiterSettings `yaml:",inline" json:",inline"`
	RootSettings    `yaml:",inline" json:",inline"`
	TraceSettings   `yaml:",inline" json:",inline"`
	// out
	GZipSettings    `yaml:",inline" json:",inline"`
	HeadersSettings `yaml:",inline" json:",inline"`
	LogSettings     `yaml:",inline" json:",inline"`
}

Settings is the main configuration struct for the HTTP server. It embeds all the other settings structs.

func (*Settings) Initialize

func (s *Settings) Initialize(ctx context.Context) error

Initialize initializes all the embedded settings structs.

func (Settings) Middleware

func (s Settings) Middleware(h http.Handler) http.Handler

Middleware returns a new http.Handler that applies all the configured middlewares.

type TraceSettings

type TraceSettings struct {
	Trace *bool `yaml:"trace" json:"trace"`
	// contains filtered or unexported fields
}

TraceSettings provides an incoming HTTP request with a unique X-Request-Id header value (only if that header wasn't present). This is particularly useful for reverse proxies that forward requests to another server. If both the forwarding (reverse proxy) and the forwarded server log the HTTP requests with the X-Request-Id value, you can correlate HTTP requests from different servers.

func (*TraceSettings) Initialize

func (ts *TraceSettings) Initialize() error

Initialize checks if the settings are valid.

func (TraceSettings) Middleware

func (ts TraceSettings) Middleware(h http.Handler) http.Handler

Middleware returns a new http.Handler that adds a unique X-Request-Id header to the request.

func (*TraceSettings) SetTraceXRequestID

func (ts *TraceSettings) SetTraceXRequestID(reqID func() string)

SetTraceXRequestID allows you to specify a non-default tracing value.

Source Files

  • auth.go
  • gzip.go
  • headers.go
  • limiter.go
  • log.go
  • root.go
  • server.go
  • settings.go
  • ssl.go
  • trace.go

Directories

Path Synopsis
cmd
echo command

Jump to

Keyboard shortcuts

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