httpserver

package
v1.88.0 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2024 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package httpserver defines a default configurable HTTP server with common routes and options.

Optional common routes are defined in the routes.go file. The routes include:

  • /ip: Returns the public IP address of the service instance.
  • /metrics: Returns Prometheus metrics (default and custom).
  • /ping: Pings the service to check if it is alive.
  • /pprof: Returns pprof profiling data for the selected profile.
  • /status: Checks and returns the health status of the service, including external services or components.

For a usage example, refer to the examples/service/internal/cli/bind.go file.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyMiddleware

func ApplyMiddleware(arg MiddlewareArgs, next http.Handler, middleware ...MiddlewareFn) http.Handler

ApplyMiddleware returns an http Handler with all middleware handler functions applied.

func LoggerMiddlewareFn

func LoggerMiddlewareFn(args MiddlewareArgs, next http.Handler) http.Handler

LoggerMiddlewareFn returns the middleware handler function to handle logs.

func RequestInjectHandler

func RequestInjectHandler(logger *zap.Logger, traceIDHeaderName string, redactFn RedactFn, next http.Handler) http.Handler

RequestInjectHandler wraps all incoming requests and injects a logger in the request scoped context.

func Start deprecated

func Start(ctx context.Context, binder Binder, opts ...Option) error

Start configures and start a new HTTP server.

Deprecated: Use New() and StartServerCtx() instead.

Types

type Binder

type Binder interface {
	// BindHTTP returns the routes.
	BindHTTP(ctx context.Context) []Route
}

Binder is an interface to allow configuring the HTTP router.

func NopBinder

func NopBinder() Binder

NopBinder returns a simple no-operation binder.

type DefaultRoute

type DefaultRoute string

DefaultRoute is the type for the default route names.

const (
	// IndexRoute is the identifier to enable the index handler.
	IndexRoute DefaultRoute = "index"

	// IPRoute is the identifier to enable the ip handler.
	IPRoute DefaultRoute = "ip"

	// MetricsRoute is the identifier to enable the metrics handler.
	MetricsRoute DefaultRoute = "metrics"

	// PingRoute is the identifier to enable the ping handler.
	PingRoute DefaultRoute = "ping"

	// PprofRoute is the identifier to enable the pprof handler.
	PprofRoute DefaultRoute = "pprof"

	// StatusRoute is the identifier to enable the status handler.
	StatusRoute DefaultRoute = "status"
)

type GetPublicIPFunc

type GetPublicIPFunc func(context.Context) (string, error)

GetPublicIPFunc is a type alias for function to get public IP of the service.

func GetPublicIPDefaultFunc

func GetPublicIPDefaultFunc() GetPublicIPFunc

GetPublicIPDefaultFunc returns the GetPublicIP function for a default ipify client.

type HTTPServer added in v1.74.0

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

HTTPServer defines the HTTP Server object.

func New added in v1.74.0

func New(ctx context.Context, binder Binder, opts ...Option) (*HTTPServer, error)

New configures new HTTP server.

func (*HTTPServer) Shutdown added in v1.74.0

func (h *HTTPServer) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections. Wraps the standard net/http/Server_Shutdown method.

func (*HTTPServer) StartServer added in v1.74.0

func (h *HTTPServer) StartServer()

StartServer starts the current server and return without blocking.

func (*HTTPServer) StartServerCtx added in v1.80.2

func (h *HTTPServer) StartServerCtx(ctx context.Context)

StartServerCtx starts the current server and return without blocking. This ignore the context passed to the New() method.

type Index

type Index struct {
	// Routes is the list of routes attached to the current service.
	Routes []Route `json:"routes"`
}

Index contains the list of routes attached to the current service.

type IndexHandlerFunc

type IndexHandlerFunc func([]Route) http.HandlerFunc

IndexHandlerFunc is a type alias for the route index function.

type InstrumentHandler

type InstrumentHandler func(string, http.HandlerFunc) http.Handler

InstrumentHandler is deprecated. Deprecated: Use instead WithMiddlewareFn.

type MiddlewareArgs

type MiddlewareArgs struct {
	// Method is the HTTP method (e.g.: GET, POST, PUT, DELETE, ...).
	Method string

	// Path is the URL path.
	Path string

	// Description is the description of the route or a general description for the handler.
	Description string

	// TraceIDHeaderName is the Trace ID header name.
	TraceIDHeaderName string

	// RedactFunc is the function used to redact HTTP request and response dumps in the logs.
	RedactFunc RedactFn

	// Logger is the logger.
	Logger *zap.Logger
}

MiddlewareArgs contains extra optional arguments to be passed to the middleware handler function MiddlewareFn.

type MiddlewareFn

type MiddlewareFn func(args MiddlewareArgs, next http.Handler) http.Handler

MiddlewareFn is a function that wraps an http.Handler.

type Option

type Option func(*config) error

Option is a type alias for a function that configures the HTTP httpServer instance.

func WithEnableAllDefaultRoutes

func WithEnableAllDefaultRoutes() Option

WithEnableAllDefaultRoutes enables all default routes on the server.

func WithEnableDefaultRoutes

func WithEnableDefaultRoutes(ids ...DefaultRoute) Option

WithEnableDefaultRoutes sets the default routes to be enabled on the server.

func WithIPHandlerFunc

func WithIPHandlerFunc(handler http.HandlerFunc) Option

WithIPHandlerFunc replaces the default ip handler function.

func WithIndexHandlerFunc

func WithIndexHandlerFunc(handler IndexHandlerFunc) Option

WithIndexHandlerFunc replaces the index handler.

func WithInstrumentHandler

func WithInstrumentHandler(handler InstrumentHandler) Option

WithInstrumentHandler is deprecated. Deprecated: Use WithMiddlewareFn instead.

func WithMethodNotAllowedHandlerFunc

func WithMethodNotAllowedHandlerFunc(handler http.HandlerFunc) Option

WithMethodNotAllowedHandlerFunc http handler called when a request cannot be routed.

func WithMetricsHandlerFunc

func WithMetricsHandlerFunc(handler http.HandlerFunc) Option

WithMetricsHandlerFunc replaces the default metrics handler function.

func WithMiddlewareFn

func WithMiddlewareFn(fn ...MiddlewareFn) Option

WithMiddlewareFn adds one or more middleware handler functions to all routes (endpoints). These middleware handlers are applied in the provided order after the default ones and before the custom route ones.

func WithNotFoundHandlerFunc

func WithNotFoundHandlerFunc(handler http.HandlerFunc) Option

WithNotFoundHandlerFunc http handler called when no matching route is found.

func WithPProfHandlerFunc

func WithPProfHandlerFunc(handler http.HandlerFunc) Option

WithPProfHandlerFunc replaces the default pprof handler function.

func WithPanicHandlerFunc

func WithPanicHandlerFunc(handler http.HandlerFunc) Option

WithPanicHandlerFunc http handler to handle panics recovered from http handlers.

func WithPingHandlerFunc

func WithPingHandlerFunc(handler http.HandlerFunc) Option

WithPingHandlerFunc replaces the default ping handler function.

func WithRedactFn

func WithRedactFn(fn RedactFn) Option

WithRedactFn set the function used to redact HTTP request and response dumps in the logs.

func WithRequestTimeout

func WithRequestTimeout(timeout time.Duration) Option

WithRequestTimeout sets a time limit for all routes after which a request receives a 503 Service Unavailable. Alternatively a custom timeout handler like http.TimeoutHandler can be added via WithMiddlewareFn().

func WithRouter

func WithRouter(r *httprouter.Router) Option

WithRouter replaces the default router used by the httpServer (mostly used for test purposes with a mock router).

func WithServerAddr

func WithServerAddr(addr string) Option

WithServerAddr sets the address the httpServer will bind to.

func WithServerReadHeaderTimeout

func WithServerReadHeaderTimeout(timeout time.Duration) Option

WithServerReadHeaderTimeout sets the read header timeout.

func WithServerReadTimeout

func WithServerReadTimeout(timeout time.Duration) Option

WithServerReadTimeout sets the read timeout.

func WithServerWriteTimeout

func WithServerWriteTimeout(timeout time.Duration) Option

WithServerWriteTimeout sets the write timeout.

func WithShutdownSignalChan added in v1.73.0

func WithShutdownSignalChan(ch chan struct{}) Option

WithShutdownSignalChan sets the shared channel uset to signal a shutdown. When the channel signal is received the server will initiate the shutdown process.

func WithShutdownTimeout

func WithShutdownTimeout(timeout time.Duration) Option

WithShutdownTimeout sets the shutdown timeout.

func WithShutdownWaitGroup added in v1.72.0

func WithShutdownWaitGroup(wg *sync.WaitGroup) Option

WithShutdownWaitGroup sets the shared waiting group to communicate externally when the server is shutdown.

func WithStatusHandlerFunc

func WithStatusHandlerFunc(handler http.HandlerFunc) Option

WithStatusHandlerFunc replaces the default status handler function.

func WithTLSCertData

func WithTLSCertData(pemCert, pemKey []byte) Option

WithTLSCertData enable TLS with the given certificate and key data.

func WithTraceIDHeaderName

func WithTraceIDHeaderName(name string) Option

WithTraceIDHeaderName overrides the default trace id header name.

func WithoutDefaultRouteLogger

func WithoutDefaultRouteLogger(routes ...DefaultRoute) Option

WithoutDefaultRouteLogger disables the logger handler for the specified default routes.

func WithoutRouteLogger

func WithoutRouteLogger() Option

WithoutRouteLogger disables the logger handler for all routes.

type RedactFn

type RedactFn func(s string) string

RedactFn is an alias for a redact function.

type Route

type Route struct {
	// Method is the HTTP method (e.g.: GET, POST, PUT, DELETE, ...).
	Method string `json:"method"`

	// Path is the URL path.
	Path string `json:"path"`

	// Description is the description of this route that is displayed by the /index endpoint.
	Description string `json:"description"`

	// Handler is the handler function.
	Handler http.HandlerFunc `json:"-"`

	// Middleware is a set of middleware to apply to this route.
	Middleware []MiddlewareFn `json:"-"`

	// DisableLogger disable the default logger when set to true.
	DisableLogger bool `json:"-"`

	// Timeout time limit after which a request receives a 503 Service Unavailable.
	// If set, overrides the common value set with WithRequestTimeout.
	Timeout time.Duration `json:"-"`
}

Route contains the HTTP route description.

type Router

type Router interface {
	http.Handler

	// Handler is an http.Handler wrapper.
	Handler(method, path string, handler http.Handler)
}

Router is deprecated. Deprecated: use *httprouter.Router instead.

Directories

Path Synopsis
Package route is deprecated.
Package route is deprecated.

Jump to

Keyboard shortcuts

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