http

package module
v0.0.0-...-7be2681 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2024 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package http provides code for managing http server lifecycle. Also includes some helpers for error handling and common middleware.

Index

Constants

This section is empty.

Variables

View Source
var DefaultLogFilter = func(r *http.Request) bool {
	return r.URL.Path == "/" || strings.HasPrefix(r.URL.Path, "/__")
}

The filter used by the DefaultRequestLogger.

Generally this will try to filter out really common endpoints, such as the root and health check endpoints.

View Source
var DefaultRequestLogger = func(log zerolog.Logger, fieldKey, headerName string) Middleware {
	return func(next http.Handler) http.Handler {
		return hlog.NewHandler(log)(
			AccessHandler(
				RequestIDHandler(fieldKey, headerName)(next),
				DefaultLogFilter,
			),
		)
	}
}

DefaultRequestLogger provides a default middleware chain with AccessHandler and RequestIDHandler middlewares

Example:

DefaultRequestLogger(log, "requestid", "Request-Id")(handler)

Functions

func AccessHandler

func AccessHandler(next http.Handler, filters ...LogFilter) http.Handler

AccessHandler is a standard request logger implementation

Any path that contains a prefix from excludedPathPrefixes will not be logged. This is useful for preventing health checks from being logged out.

func CtxWithSignal

func CtxWithSignal(ctx context.Context, sig ...os.Signal) context.Context

CtxWithSignal returns a context that completes when one of the os Signals is received. Leaving sig empty will default to SIGTERM, SIGQUIT and SIGINT

func IDFromCtx

func IDFromCtx(ctx context.Context) (string, bool)

IDFromCtx returns the unique id associated to the context if any.

func IDFromRequest

func IDFromRequest(r *http.Request, headerName string) (string, bool)

IDFromRequest returns the unique id associated with the request. This is retrieved from the context or a header on the incoming request if available.

func NewErr

func NewErr(status int, msg string) errResponse

NewErr returns a masked error response with ID and human-readable message. The ID can be used to associate the response with a server log record to reconstruct the full error message.

func RequestErr

func RequestErr(status int, log zerolog.Logger, w http.ResponseWriter, err error, msg string)

RequestErr handles logs an error and writes an error response

Types

type HealthOptions

type HealthOptions struct {
	Path    string
	AppName string
	Version string
}

type LogFilter

type LogFilter func(r *http.Request) bool

Used with logging handlers. Returns true if the request should NOT be logged.

type Middleware

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

Middleware represents a func that chains http handlers

func RequestIDHandler

func RequestIDHandler(fieldKey, headerName string) Middleware

RequestIDHandler returns a handler setting a unique id on the request which can be retrieved using IDFromRequest(req). This generated id is added as a field to the logger using the passed fieldKey as field name. The id is also added as a response header if the headerName is not empty.

type Option

type Option func(*Server)

Option configures a Server instance

func WithAddr

func WithAddr(addr string) Option

WithAddr returns an Option to configure server listen address

func WithHandler

func WithHandler(h http.Handler) Option

WithHandler returns an Option to configure the server's http handler

func WithHealth

func WithHealth(h HealthOptions) Option

WithHealth returns an Option to configure the server healthcheck endpoint

func WithLogger

func WithLogger(l zerolog.Logger) Option

WithLogger returns an Option to configure server logger instance

func WithStopTimeout

func WithStopTimeout(d time.Duration) Option

WithStopTimeout returns an Option to configure the duration to wait for connections to terminate on shutdown

type Server

type Server struct {
	Srv     *http.Server
	Running bool
	// contains filtered or unexported fields
}

Server manages the lifecycle of an http API server with graceful shutdown

Example:

srv := http.New()
if err := srv.Start(ctx); err != nil {
	// handle server runtime err
}
if err := s.Stop(); err != nil {
	// handle server close err
}

func New

func New(opts ...Option) *Server

New constructs a server

func (*Server) ErrBadRequest

func (s *Server) ErrBadRequest(w http.ResponseWriter, err error, msg string)

ErrBadRequest writes a bad request err response

func (*Server) ErrInternal

func (s *Server) ErrInternal(w http.ResponseWriter, err error, msg string)

ErrInternal writes an internal err response

func (*Server) ErrNotFound

func (s *Server) ErrNotFound(w http.ResponseWriter, err error, msg string)

ErrNotFound writes a not found err response

func (*Server) Health

func (s *Server) Health(h HealthOptions) http.Handler

Health returns a handler for healthcheck requests

func (*Server) Start

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

Start starts the server listening, will block on signal or error

func (*Server) Stop

func (s *Server) Stop() error

Stop stops the running server

Jump to

Keyboard shortcuts

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