http

package
v0.52.0 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2026 License: Apache-2.0 Imports: 34 Imported by: 0

Documentation

Overview

Example

Example demonstrates encoding and decoding structs to/from HTTP headers

package main

import (
	"fmt"
	"log"

	dhttp "github.com/dioad/net/http"
)

func main() {
	// Define a struct to encode
	type RequestMetadata struct {
		User    string
		Session string
		Tags    []string
	}

	metadata := RequestMetadata{
		User:    "user-123",
		Session: "session-456",
		Tags:    []string{"tag1", "tag2", "tag3"},
	}

	// Configure marshaling with a prefix and struct name
	opts := dhttp.HeaderMarshalOptions{
		Prefix:            "X",
		IncludeStructName: true,
	}

	// Marshal to HTTP header
	headers, err := dhttp.MarshalHeader(metadata, opts)
	if err != nil {
		log.Fatal(err)
	}

	// Print the headers
	fmt.Println("Encoded headers:")
	fmt.Printf("  X-Request-Metadata-User: %s\n", headers.Get("X-Request-Metadata-User"))
	fmt.Printf("  X-Request-Metadata-Session: %s\n", headers.Get("X-Request-Metadata-Session"))
	fmt.Printf("  X-Request-Metadata-Tags: %v\n", headers.Values("X-Request-Metadata-Tags"))

	// Unmarshal back to a struct
	var decoded RequestMetadata
	err = dhttp.UnmarshalHeader(headers, &decoded, opts)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("\nDecoded struct:\n")
	fmt.Printf("  User: %s\n", decoded.User)
	fmt.Printf("  Session: %s\n", decoded.Session)
	fmt.Printf("  Tags: %v\n", decoded.Tags)

}
Output:

Encoded headers:
  X-Request-Metadata-User: user-123
  X-Request-Metadata-Session: session-456
  X-Request-Metadata-Tags: [tag1 tag2 tag3]

Decoded struct:
  User: user-123
  Session: session-456
  Tags: [tag1 tag2 tag3]

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddMapToHTTPHeader

func AddMapToHTTPHeader(baseHeaders http.Header, headerMap map[string]string) http.Header

AddMapToHTTPHeader adds a map[string]string to an existing http.Header

func CORSAllowLocalhostOrigin added in v0.50.4

func CORSAllowLocalhostOrigin(origin string) bool

func CORSHandler added in v0.50.4

func CORSHandler(options cors.Options) (mux.MiddlewareFunc, error)

func CreateHTTPHeaderFromMap

func CreateHTTPHeaderFromMap(headerMap map[string]string) http.Header

CreateHTTPHeaderFromMap creates a new http.Header from a map[string]string

func MarshalHeader added in v0.52.0

func MarshalHeader(v interface{}, opts HeaderMarshalOptions) (http.Header, error)

MarshalHeader encodes a struct into an http.Header using the provided options.

RFC 9110 Compliance: For slice fields ([]string), each element is added as a separate header occurrence using http.Header.Add(). This is compliant with RFC 9110 Section 5.5, which allows multiple header field lines with the same name. Values containing commas, quotes, or other special characters are preserved as-is in each occurrence.

Example:

type Example struct {
    Values []string
}
ex := Example{Values: []string{"val1", "val2,with,comma"}}
// Produces:
// X-Values: val1
// X-Values: val2,with,comma
Example (CustomTags)

ExampleMarshalHeader_customTags demonstrates using custom header tags

package main

import (
	"fmt"
	"log"

	dhttp "github.com/dioad/net/http"
)

func main() {
	type Metadata struct {
		RequestID string `header:"request-id"`
		TraceID   string `header:"trace-id"`
		Internal  string `header:"-"` // This field will be ignored
	}

	metadata := Metadata{
		RequestID: "req-789",
		TraceID:   "trace-abc",
		Internal:  "should-not-appear",
	}

	opts := dhttp.DefaultHeaderMarshalOptions()

	headers, err := dhttp.MarshalHeader(metadata, opts)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Headers with custom tags:")
	fmt.Printf("  request-id: %s\n", headers.Get("request-id"))
	fmt.Printf("  trace-id: %s\n", headers.Get("trace-id"))
	fmt.Printf("  internal present: %v\n", headers.Get("internal") != "")

}
Output:

Headers with custom tags:
  request-id: req-789
  trace-id: trace-abc
  internal present: false
Example (Rfc9110Compliance)

ExampleMarshalHeader_rfc9110Compliance demonstrates RFC 9110 compliance for handling multiple header occurrences

package main

import (
	"fmt"

	dhttp "github.com/dioad/net/http"
)

func main() {
	type DataList struct {
		Items []string
	}

	// Data with values containing commas
	data := DataList{
		Items: []string{"item1", "item2,with,comma", "item3"},
	}

	opts := dhttp.DefaultHeaderMarshalOptions()

	// Marshal to headers
	headers, _ := dhttp.MarshalHeader(data, opts)

	// Show how multiple occurrences are created (RFC 9110 Section 5.5)
	fmt.Println("Multiple header occurrences:")
	for _, item := range headers.Values("items") {
		fmt.Printf("  items: %s\n", item)
	}

	// Unmarshal back - values are preserved exactly
	var result DataList
	dhttp.UnmarshalHeader(headers, &result, opts)

	fmt.Printf("\nUnmarshaled values:\n")
	for i, item := range result.Items {
		fmt.Printf("  [%d]: %s\n", i, item)
	}

}
Output:

Multiple header occurrences:
  items: item1
  items: item2,with,comma
  items: item3

Unmarshaled values:
  [0]: item1
  [1]: item2,with,comma
  [2]: item3
Example (WithoutStructName)

ExampleMarshalHeader_withoutStructName demonstrates encoding without the struct name in headers

package main

import (
	"fmt"
	"log"

	dhttp "github.com/dioad/net/http"
)

func main() {
	type Config struct {
		ApiKey string
		Region string
	}

	config := Config{
		ApiKey: "secret-key",
		Region: "us-west-2",
	}

	// Configure without struct name
	opts := dhttp.HeaderMarshalOptions{
		Prefix:            "X",
		IncludeStructName: false,
	}

	headers, err := dhttp.MarshalHeader(config, opts)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Headers without struct name:")
	fmt.Printf("  X-Api-Key: %s\n", headers.Get("X-Api-Key"))
	fmt.Printf("  X-Region: %s\n", headers.Get("X-Region"))

}
Output:

Headers without struct name:
  X-Api-Key: secret-key
  X-Region: us-west-2

func NewPersistentCookieStore

func NewPersistentCookieStore(config CookieConfig) (*sessions.CookieStore, error)

func NewSessionCookieStore

func NewSessionCookieStore(config CookieConfig) (*sessions.CookieStore, error)

func NewUnixSocketClient added in v0.39.0

func NewUnixSocketClient(path string) *http.Client

func OAuth2ValidatorHandler added in v0.50.4

func OAuth2ValidatorHandler(v []oidc.ValidatorConfig) (mux.MiddlewareFunc, error)

func StandardLogger added in v0.36.1

func StandardLogger(r *http.Request, status, size int, duration time.Duration) *zerolog.Logger

StandardLogger creates a zerolog.Logger with standard fields for HTTP access logging.

func UnmarshalHeader added in v0.52.0

func UnmarshalHeader(header http.Header, v interface{}, opts HeaderMarshalOptions) error

UnmarshalHeader decodes an http.Header into a struct using the provided options.

RFC 9110 Compliance: Multiple header field occurrences with the same name are unmarshaled into slice fields ([]string) using http.Header.Values(). This retrieves all values for the header in the order they were added, preserving the semantics defined in RFC 9110 Section 5.5. Each value is kept as-is without parsing commas or other delimiters.

Example:

// Given headers:
// X-Values: val1
// X-Values: val2,with,comma
type Example struct {
    Values []string
}
var ex Example
UnmarshalHeader(headers, &ex, opts)
// Results in: ex.Values = []string{"val1", "val2,with,comma"}
Example (Middleware)

ExampleUnmarshalHeader_middleware demonstrates using header marshaling in HTTP middleware

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	dhttp "github.com/dioad/net/http"
)

func main() {
	type RequestContext struct {
		TenantId string
		UserRole string
	}

	// Create a middleware that decodes headers into a struct
	middleware := func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			opts := dhttp.HeaderMarshalOptions{
				Prefix:            "X-Context",
				IncludeStructName: false,
			}

			var ctx RequestContext
			if err := dhttp.UnmarshalHeader(r.Header, &ctx, opts); err != nil {
				http.Error(w, "Invalid context headers", http.StatusBadRequest)
				return
			}

			// Use the decoded context
			fmt.Printf("Processing request for tenant: %s, role: %s\n", ctx.TenantId, ctx.UserRole)
			next.ServeHTTP(w, r)
		})
	}

	// Create a simple handler
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	// Wrap with middleware
	wrappedHandler := middleware(handler)

	// Simulate a request with headers
	req, _ := http.NewRequest("GET", "/api/data", nil)
	req.Header.Set("X-Context-Tenant-Id", "tenant-123")
	req.Header.Set("X-Context-User-Role", "admin")

	// Create a response recorder
	w := httptest.NewRecorder()

	// Process the request
	wrappedHandler.ServeHTTP(w, req)

}
Output:

Processing request for tenant: tenant-123, role: admin

Types

type Client

type Client struct {
	Config *ClientConfig
}

func NewClient

func NewClient(config *ClientConfig) *Client

func NewDefaultClient

func NewDefaultClient() *Client

func (*Client) Request

func (c *Client) Request(req *http.Request) (*http.Response, error)

func (*Client) ResolveRelativeRequestPath

func (c *Client) ResolveRelativeRequestPath(requestPath string) (*url.URL, error)

type ClientConfig

type ClientConfig struct {
	BaseURL    *url.URL
	Client     *http.Client
	UserAgent  string
	AuthConfig auth.ClientConfig
}

type Config

type Config struct {
	// ListenAddress is the address to listen on, e.g. ":8080"
	ListenAddress string
	// EnablePrometheusMetrics enables the /metrics endpoint for Prometheus metrics
	EnablePrometheusMetrics bool
	// EnableDebug enables the /debug endpoint for pprof debugging
	EnableDebug bool
	// EnableStatus enables the /status endpoint for server status
	EnableStatus bool
	// EnableProxyProtocol enables the PROXY protocol for client IP forwarding
	EnableProxyProtocol bool
	// TLSConfig is the TLS configuration for the server
	TLSConfig *tls.Config
	// AuthConfig is the authentication configuration for the server
	AuthConfig auth.ServerConfig
}

Config represents the configuration for an HTTP server

type CookieConfig

type CookieConfig struct {
	Base64AuthenticationKey string `mapstructure:"base64-authentication-key"`
	Base64EncryptionKey     string `mapstructure:"base64-encryption-key"`
	MaxAge                  int    `mapstructure:"max-age"`
	Domain                  string `mapstructure:"domain"`
}

type DefaultResource

type DefaultResource interface {
	RegisterRoutes(*mux.Router)
}

type EnforceTLSHandler added in v0.37.0

type EnforceTLSHandler struct {
	EnforceTLS bool
}

func (*EnforceTLSHandler) Wrap added in v0.37.0

func (h *EnforceTLSHandler) Wrap(handler http.Handler) http.Handler

type HandlerWrapper

type HandlerWrapper func(next http.Handler) http.Handler

func DefaultCombinedLogHandler

func DefaultCombinedLogHandler(logWriter io.Writer) HandlerWrapper

DefaultCombinedLogHandler returns a HandlerWrapper that logs HTTP requests using the combined log format.

func ZerologStructuredLogHandler

func ZerologStructuredLogHandler(logger zerolog.Logger) HandlerWrapper

ZerologStructuredLogHandler returns a HandlerWrapper that uses zerolog for structured logging.

func ZerologStructuredLogHandlerWithFormatter added in v0.36.1

func ZerologStructuredLogHandlerWithFormatter(logger zerolog.Logger, formatter StructuredLoggerFormatter) HandlerWrapper

ZerologStructuredLogHandlerWithFormatter returns a HandlerWrapper that uses a custom formatter for structured logging.

type HeaderMarshalOptions added in v0.52.0

type HeaderMarshalOptions struct {
	// Prefix is prepended to all header names (e.g., "X" results in "X-Field-Name")
	Prefix string
	// IncludeStructName includes the struct type name in the header (e.g., "X-Example-Field-Name")
	IncludeStructName bool
}

HeaderMarshalOptions configures how structs are marshaled to and from http.Header

func DefaultHeaderMarshalOptions added in v0.52.0

func DefaultHeaderMarshalOptions() HeaderMarshalOptions

DefaultHeaderMarshalOptions returns default options with no prefix and no struct name

type LogLevelSetter added in v0.48.0

type LogLevelSetter interface {
	// SetLogLevel sets the global log level for zerolog.
	SetLogLevel(level string) error
	// SetLogLevelWithDuration sets the global log level for zerolog and returns the time when it expires.
	SetLogLevelWithDuration(level string, duration time.Duration) (time.Time, error)
	// OriginalLogLevel returns the original log level before any changes.
	OriginalLogLevel() string
	// CurrentLogLevel returns the current log level.
	CurrentLogLevel() string
	// ResetLogLevel resets the log level to the original level.
	ResetLogLevel()
	// ExpiresAt returns the time when the current log level will expire.
	ExpiresAt() time.Time
}

LogLevelSetter defines an interface for setting and managing log levels.

func NewZeroLogLevelSetter added in v0.48.0

func NewZeroLogLevelSetter() LogLevelSetter

NewZeroLogLevelSetter creates a new LogLevelSetter for zerolog.

type MetricSet

type MetricSet struct {
	RequestCounter  *prometheus.CounterVec
	RequestDuration *prometheus.HistogramVec
	RequestSize     *prometheus.HistogramVec
	ResponseSize    *prometheus.HistogramVec
	InFlightGauge   prometheus.Gauge
}

func NewMetricSet

func NewMetricSet(r *prometheus.Registry) *MetricSet

func (*MetricSet) Middleware

func (m *MetricSet) Middleware(next http.Handler) http.Handler

Middleware - to make it a middleware for mux probably a better way. TODO: need to extract this from this struct to remove the coupling with mux

func (*MetricSet) Register

func (m *MetricSet) Register(r prometheus.Registerer)

type PathResource

type PathResource interface {
	RegisterRoutesWithPrefix(*mux.Router, string)
}

type Resource

type Resource interface{}

type RootResource

type RootResource interface {
	// Resource
	Index() http.HandlerFunc
}

type Server

type Server struct {
	// Config is the server configuration
	Config Config
	// Router is the main router for the server
	Router *mux.Router
	// Logger is the logger for the server
	Logger zerolog.Logger
	// ResourceMap maps path prefixes to resources
	ResourceMap map[string]Resource
	// ListenAddr is the address the server is listening on
	ListenAddr net.Addr
	// LogHandler is the handler wrapper for logging requests
	LogHandler HandlerWrapper
	// contains filtered or unexported fields
}

Server represents an HTTP server with various features like metrics, authentication, and resources

func NewServer

func NewServer(config Config, opts ...ServerOption) *Server

NewServer creates a new HTTP server with the given configuration and options Options can be used to customize the server, such as adding a logger, authentication, or metrics

func (*Server) AddHandler

func (s *Server) AddHandler(path string, handler http.Handler)

AddHandler adds a handler for the specified path

func (*Server) AddHandlerFunc

func (s *Server) AddHandlerFunc(path string, handler http.HandlerFunc)

AddHandlerFunc adds a handler function for the specified path

func (*Server) AddResource

func (s *Server) AddResource(pathPrefix string, r Resource, middlewares ...mux.MiddlewareFunc)

AddResource adds a resource to the server at the specified path prefix The resource can implement either PathResource or DefaultResource to register its routes Optional middlewares can be provided to be applied to the resource's routes

func (*Server) AddRootResource

func (s *Server) AddRootResource(r RootResource)

AddRootResource sets the root resource for the server The root resource's Index method will be called for any path that doesn't match other routes

func (*Server) AddStatusStaticMetadataItem

func (s *Server) AddStatusStaticMetadataItem(key string, value any)

AddStatusStaticMetadataItem adds a static metadata item to the status endpoint These items will be included in the "Metadata" section of the status response

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe starts the server with the TLS configuration from the server's config It creates a listener on the configured address and calls Serve

func (*Server) ListenAndServeTLS

func (s *Server) ListenAndServeTLS(tlsConfig *tls.Config) error

ListenAndServeTLS starts the server with the provided TLS configuration The tlsConfig will override any prior configuration in s.Config It creates a listener on the configured address and calls Serve

func (*Server) RegisterOnShutdown

func (s *Server) RegisterOnShutdown(f func())

RegisterOnShutdown registers a function to be called when the server is shutting down This function will be called in a new goroutine when Shutdown is called

func (*Server) Serve

func (s *Server) Serve(ln net.Listener) error

Serve starts the server with the provided listener It initializes the server if needed, configures TLS and proxy protocol if enabled, and starts serving HTTP or HTTPS requests

func (*Server) ServeTLS

func (s *Server) ServeTLS(ln net.Listener) error

ServeTLS is a convenience method that calls Serve It's provided for compatibility with the http.Server interface

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections It waits for all connections to finish or for the context to be canceled

func (*Server) Use added in v0.43.0

func (s *Server) Use(middlewares ...mux.MiddlewareFunc)

Use adds middleware to the server's router Any nil middlewares will be filtered out

type ServerOption added in v0.43.0

type ServerOption func(*Server)

ServerOption is a function that configures a Server

func WithCORS added in v0.50.3

func WithCORS(options cors.Options) ServerOption

func WithLogWriter added in v0.43.0

func WithLogWriter(w io.Writer) ServerOption

WithLogWriter returns a ServerOption that configures the server to log requests to the given writer using the combined log format

func WithLogger added in v0.43.0

func WithLogger(l zerolog.Logger) ServerOption

WithLogger returns a ServerOption that configures the server to use the given logger for both server logs and request logs

func WithOAuth2Validator added in v0.43.0

func WithOAuth2Validator(v []oidc.ValidatorConfig) ServerOption

WithOAuth2Validator returns a ServerOption that configures the server to use OAuth2 validation for authentication using the given validator configurations

func WithPrometheusRegistry added in v0.46.0

func WithPrometheusRegistry(r prometheus.Registerer) ServerOption

WithPrometheusRegistry returns a ServerOption that configures the server to register its metrics with the given Prometheus registry

func WithServerAuth added in v0.46.0

func WithServerAuth(cfg auth.ServerConfig) ServerOption

WithServerAuth returns a ServerOption that configures the server to use the given authentication configuration

func WithTelemetryInstrument added in v0.46.0

func WithTelemetryInstrument(i middleware.Instrument) ServerOption

WithTelemetryInstrument returns a ServerOption that configures the server to use the given telemetry instrument for metrics collection

type StatusResource

type StatusResource interface {
	Status() (interface{}, error)
}

type StructuredLoggerFormatter added in v0.36.1

type StructuredLoggerFormatter func(r *http.Request, status, size int, duration time.Duration) *zerolog.Logger

type UseResource added in v0.43.1

type UseResource interface {
	Use(...mux.MiddlewareFunc) UseResource
}

Directories

Path Synopsis
jwt
authz
ip
jwt

Jump to

Keyboard shortcuts

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