httputil

package
v0.0.0-...-59817e7 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2025 License: MIT Imports: 11 Imported by: 2

Documentation

Overview

Package httputil provides utilities for writing http services.

Index

Constants

View Source
const (
	// HeaderUsername is the header set by the auth system (reverse proxy) to denote the username
	HeaderUsername = "X-Auth-Username"

	// HeaderInstance is a header used for identify this unique request/response (primitive tracing)
	HeaderInstance = "X-Instance"

	// HeaderCreationDate denotes the date at which this item was first uploaded to the telemetry server (used for replication purposes)
	HeaderCreationDate = "X-Creation-Date"
)
View Source
const (
	// MediaTypeProblem is the content type for errors produced by the server
	MediaTypeProblem = "application/problem+json; charset=utf-8"
)

Variables

This section is empty.

Functions

func AllowCaching

func AllowCaching(headers http.Header)

AllowCaching adds caching headers

func AllowContentTypeMiddleware

func AllowContentTypeMiddleware(next http.Handler, contentTypes ...string) http.Handler

AllowContentTypeMiddleware enforces a allowlist of request Content-Types

func InstanceFromContext

func InstanceFromContext(ctx context.Context) uuid.UUID

InstanceFromContext returns the instance for this request to uniquely identify the request

func RecovererMiddleware

func RecovererMiddleware(next http.Handler) http.Handler

RecovererMiddleware is a middleware that recovers from panics, logs the panic (and a backtrace), and returns a HTTP 500 (Internal Server Error) status if possible. Recoverer prints a request ID if one is provided.

KMT - I am not sure we need this middleware since the golang server already recovers from panics. It just does not use our logger or return a 500.

func Serve

func Serve(ctx context.Context, srv *http.Server, timeout time.Duration) error

Serve will run the http server until the context is done. Then it gracefully shutdown.

func TimeoutMiddleware

func TimeoutMiddleware(next http.Handler, timeout time.Duration) http.Handler

TimeoutMiddleware cancels the request context after a given timeout duration

func TracingMiddleware

func TracingMiddleware(next http.Handler) http.Handler

TracingMiddleware injects a tracing ID into the context

func WriteJSON

func WriteJSON(w http.ResponseWriter, obj any) error

WriteJSON writes obj as JSON to the response

Types

type Client

type Client interface {
	Do(req *http.Request) (*http.Response, error)
}

Client is an interface for HTTP clients.

func WithRequestEditors

func WithRequestEditors(client Client, editors ...func(req *http.Request) error) Client

WithRequestEditors wraps a Client with request editor functions (RequestEditorFunc).

Each given RequestEditorFunc will be called to modify the request before it is handled by [Client.Do].

If a RequestEditorFunc returns an error, the error will be returned and the underlying [Client.Do] will not be called.

func WrapClient

func WrapClient(client Client, middlewares ...ClientMiddlewareFunc) Client

WrapClient wraps a Client with client middlewares.

type ClientError

type ClientError interface {
	Error() string
	// Extra KeyValue pairs associated with the error
	ErrorArgs() []any
	// ResponseBody returns response body.
	ResponseBody() ([]byte, error)
	// ResponseHeaders returns http status code and headers.
	ResponseHeaders() (int, map[string]string)
}

ClientError is an error whose details to be shared with client.

type ClientFunc

type ClientFunc func(req *http.Request) (*http.Response, error)

ClientFunc promotes a function to a Client.

func (ClientFunc) Do

func (client ClientFunc) Do(req *http.Request) (*http.Response, error)

Do implements Client.

type ClientMiddlewareFunc

type ClientMiddlewareFunc = func(next Client) Client

ClientMiddlewareFunc is an alias for client middleware functions.

type HTTPError

type HTTPError struct {
	Cause      error  `json:"-"`
	CauseArgs  []any  `json:"-"`
	Detail     string `json:"detail"`
	StatusCode int    `json:"-"`
	Status     string `json:"status"`
}

HTTPError implements ClientError interface.

func NewHTTPError

func NewHTTPError(err error, statusCode int, detail string, extraKV ...any) *HTTPError

NewHTTPError returns a new error

func (*HTTPError) Error

func (e *HTTPError) Error() string

func (*HTTPError) ErrorArgs

func (e *HTTPError) ErrorArgs() []any

ErrorArgs returns extra KV args for logging the error

func (*HTTPError) LogValue

func (e *HTTPError) LogValue() slog.Value

LogValue implements log/slog.LogValuer.

func (*HTTPError) ResponseBody

func (e *HTTPError) ResponseBody() ([]byte, error)

ResponseBody returns JSON response body.

func (*HTTPError) ResponseHeaders

func (e *HTTPError) ResponseHeaders() (int, map[string]string)

ResponseHeaders returns http status code and headers.

type MiddlewareFunc

type MiddlewareFunc func(http.Handler) http.Handler

MiddlewareFunc is an alias for middleware functions.

func LoggingMiddleware

func LoggingMiddleware(log *slog.Logger) MiddlewareFunc

LoggingMiddleware injects a logger into the context.

A previous implementation contained a memory leak because the tracing attributes were always appended to the given logger.

func ServerHeaderMiddleware

func ServerHeaderMiddleware(server string) MiddlewareFunc

ServerHeaderMiddleware injects the Server into the response headers

type RequestEditorFunc

type RequestEditorFunc = func(req *http.Request) error

RequestEditorFunc edits HTTP requests.

func WithBasicAuth

func WithBasicAuth(username, password string) RequestEditorFunc

WithBasicAuth produces a RequestEditorFunc that sets basic auth with http.Request.SetBasicAuth for all requests.

type RootHandler

type RootHandler func(http.ResponseWriter, *http.Request) error

RootHandler a wrapper around the handler functions to allow uniform error handling

func (RootHandler) ServeHTTP

func (fn RootHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

RootHandler implements http.Handler interface.

type RouteMiddlewareFunc

type RouteMiddlewareFunc func(pattern string, handler http.Handler) http.Handler

RouteMiddlewareFunc modifies a handler as it is registered with a router.

func WrapMiddleware

func WrapMiddleware(middleware MiddlewareFunc) RouteMiddlewareFunc

WrapMiddleware adapts a MiddlewareFunc to a RouteMiddlewareFunc by ignoring the pattern argument

type Router

type Router interface {
	Handle(pattern string, handler http.Handler)
	http.Handler
}

Router represents an HTTP request server like http.ServeMux.

func WrapHandler

func WrapHandler(mux Router, middlewares ...MiddlewareFunc) Router

WrapHandler wraps a [ServeMuxer] with middlewares.

func WrapRouter

func WrapRouter(mux Router, middlewares ...RouteMiddlewareFunc) Router

WrapRouter wraps a Router with RouteMiddleware functions.

Directories

Path Synopsis
Package promhttputil contains a prometheus metrics middleware, relocated from httputil.
Package promhttputil contains a prometheus metrics middleware, relocated from httputil.

Jump to

Keyboard shortcuts

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