httpserver

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2026 License: MIT Imports: 5 Imported by: 3

Documentation

Overview

Package httpserver contains utilities for HTTP servers using the standard library. It includes a collection of middlewares and utilities for returning JSON-formatted responses and errors.

Index

Constants

View Source
const (
	HeaderXHostID     = "X-Host-Id"
	HeaderContentType = "Content-Type"
	ContentTypeJson   = "application/json; charset=utf-8"
)

Variables

This section is empty.

Functions

func RespondWithJSON

func RespondWithJSON(w http.ResponseWriter, r *http.Request, data any)

func Use

func Use(h http.Handler, middlewares ...Middleware) http.Handler

Use applies middlewares to the handler

func UseFunc

func UseFunc(h http.HandlerFunc, middlewares ...MiddlewareFunc) http.HandlerFunc

UseFunc applies middlewares (of type http.HandlerFunc) to the handler

func WithInnerError

func WithInnerError(innerError error) func(*ApiError)

WithInnerError returns a function that sets the InnerError field on an ApiError. This is typically used with the Clone method to add an underlying error cause to an API error response.

func WithMetadata

func WithMetadata(metadata map[string]string) func(*ApiError)

WithMetadata returns a function that sets the Metadata field on an ApiError. This is typically used with the Clone method to add additional context or debugging information to an API error response.

Types

type ApiError

type ApiError struct {
	Code       string            `json:"code"`
	Message    string            `json:"message"`
	InnerError string            `json:"innerError,omitempty"`
	Metadata   map[string]string `json:"metadata,omitempty"`
	// contains filtered or unexported fields
}

ApiError represents a structured API error response that can be serialized to JSON.

func NewApiError

func NewApiError(code string, httpStatus int, message string) ApiError

NewApiError creates a new ApiError with the specified code, HTTP status, and message. The HTTP status code determines what status will be written to the response when WriteResponse is called.

func (ApiError) Clone

func (e ApiError) Clone(with ...func(*ApiError)) ApiError

Clone creates a deep copy of the ApiError and optionally applies modifications through the provided functions. This is useful for creating variations of an error without modifying the original. The with parameter accepts functions like WithInnerError and WithMetadata to customize the cloned error.

func (ApiError) Error

func (e ApiError) Error() string

Error implements the error interface, returning a formatted string representation of the API error that includes both the error code and message.

func (ApiError) Is

func (e ApiError) Is(target error) bool

Is implements error comparison by checking if the target error is an ApiError with the same error code. This allows using errors.Is() to compare API errors based on their code rather than pointer equality.

func (ApiError) WriteResponse

func (e ApiError) WriteResponse(w http.ResponseWriter, r *http.Request)

WriteResponse writes the ApiError as a JSON response to the HTTP response writer. It sets the Content-Type header to application/json, writes the appropriate HTTP status code, and serializes the error as JSON in the response body.

type Middleware

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

Middleware type is a function that takes an http.Handler and returns another http.Handler

func MiddlewareHostIDHeader

func MiddlewareHostIDHeader(hostID string) Middleware

MiddlewareHostIDHeader is a middleware that adds the X-Host-ID header

func MiddlewareMaxBodySize

func MiddlewareMaxBodySize(maxSize int64) Middleware

MiddlewareMaxBodySize is a middleware that limits the size of the request body

type MiddlewareFunc

type MiddlewareFunc func(next http.HandlerFunc) http.HandlerFunc

MiddlewareFunc type is a function that takes an http.HandlerFunc and returns another http.HandlerFunc

type Mux

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

Mux extends http.ServeMux with support for route groups, path prefixes, and per-group middlewares It implements http.Handler so it can be passed wherever an http.Handler is expected The zero value is not usable Construct one with NewMux or NewMuxFromServeMux

func NewMux

func NewMux() *Mux

NewMux returns a Mux backed by a fresh http.ServeMux

func NewMuxFromServeMux

func NewMuxFromServeMux(mux *http.ServeMux) *Mux

NewMuxFromServeMux wraps an existing *http.ServeMux Useful when other code already holds a ServeMux and registers routes on it directly

func (*Mux) Group

func (m *Mux) Group(prefix string, middlewares ...Middleware) *Mux

Group returns a sub-Mux that shares the same underlying ServeMux but prepends prefix to all routes registered through it The new group inherits a snapshot of the parent's middlewares: later changes to the parent (e.g. additional sub-groups) do not affect this group The middlewares passed here are inner of (i.e. wrapped by) the parent's middlewares Within the supplied list the last entry is outermost, matching the semantics of the package-level Use function

func (*Mux) Handle

func (m *Mux) Handle(pattern string, handler http.Handler, middlewares ...Middleware)

Handle registers handler for the given pattern The pattern follows the standard library format: "[METHOD ][HOST]/PATH" The group's prefix is inserted before PATH (PATH is given a leading slash if missing) Per-route middlewares apply inside the group's middlewares (they are wrapped by them) Within the per-route list the last entry is outermost

func (*Mux) HandleFunc

func (m *Mux) HandleFunc(pattern string, handler http.HandlerFunc, middlewares ...Middleware)

HandleFunc is the http.HandlerFunc variant of Handle

func (*Mux) ServeHTTP

func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler by delegating to the underlying ServeMux

func (*Mux) ServeMux

func (m *Mux) ServeMux() *http.ServeMux

ServeMux returns the underlying *http.ServeMux

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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