baseapp

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2021 License: Apache-2.0 Imports: 21 Imported by: 26

Documentation

Overview

Package baseapp provides structure for building web application servers. It select dependencies, provides default middleware, and defines several common types, but is otherwise unopinionated.

Index

Constants

View Source
const (
	MetricsKeyRequests    = "server.requests"
	MetricsKeyRequests2xx = "server.requests.2xx"
	MetricsKeyRequests3xx = "server.requests.3xx"
	MetricsKeyRequests4xx = "server.requests.4xx"
	MetricsKeyRequests5xx = "server.requests.5xx"

	MetricsKeyNumGoroutines = "server.goroutines"
	MetricsKeyMemoryUsed    = "server.mem.used"
)

Variables

This section is empty.

Functions

func AccessHandler added in v0.2.0

func AccessHandler(f AccessCallback) func(next http.Handler) http.Handler

AccessHandler returns a handler that call f after each request.

func CountRequest

func CountRequest(r *http.Request, status int, _ int64, _ time.Duration)

CountRequest is an AccessCallback that records metrics about the request.

func DefaultMiddleware

func DefaultMiddleware(logger zerolog.Logger, registry metrics.Registry) []func(http.Handler) http.Handler

DefaultMiddleware returns the default middleware stack. The stack:

  • Adds a logger to request contexts
  • Adds a metrics registry to request contexts
  • Adds a request ID to all requests and responses
  • Logs and records metrics for all requests
  • Handles errors returned by route handlers
  • Recovers from panics in route handlers

All components are exported so users can select individual middleware to build their own stack if desired.

func HandleRouteError

func HandleRouteError(w http.ResponseWriter, r *http.Request, err error)

HandleRouteError is a hatpear error handler that logs the error and sends an error response to the client. If the error has a `StatusCode` function this will be called and converted to an appropriate HTTP status code error.

func LogRequest

func LogRequest(r *http.Request, status int, size int64, elapsed time.Duration)

LogRequest is an AccessCallback that logs request information.

func MetricsCtx

func MetricsCtx(ctx context.Context) metrics.Registry

MetricsCtx gets a metrics registry from the context. It returns the default registry from the go-metrics package if none exists in the context.

func NewLogger

func NewLogger(c LoggingConfig) zerolog.Logger

NewLogger returns a zerolog logger based on the conventions in a LoggingConfig

func NewMetricsHandler

func NewMetricsHandler(registry metrics.Registry) func(http.Handler) http.Handler

NewMetricsHandler returns middleware that add the given metrics registry to the request context.

func RecordRequest

func RecordRequest(r *http.Request, status int, size int64, elapsed time.Duration)

RecordRequest is an AccessCallback that logs request information and records request metrics.

func RegisterDefaultMetrics

func RegisterDefaultMetrics(registry metrics.Registry)

RegisterDefaultMetrics adds the default metrics provided by this package to the registry. This should be called before any functions emit metrics to ensure that no events are lost.

func RichErrorMarshalFunc

func RichErrorMarshalFunc(err error) interface{}

RichErrorMarshalFunc is a zerolog error marshaller that formats the error as a string that includes a stack trace, if one is available.

func WithMetricsCtx

func WithMetricsCtx(ctx context.Context, registry metrics.Registry) context.Context

WithMetricsCtx stores a metrics registry in a context.

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, obj interface{})

WriteJSON writes a JSON response or an error if mashalling the object fails.

Types

type AccessCallback added in v0.2.0

type AccessCallback func(r *http.Request, status int, size int64, duration time.Duration)

type HTTPConfig

type HTTPConfig struct {
	Address   string     `yaml:"address" json:"address"`
	Port      int        `yaml:"port" json:"port"`
	PublicURL string     `yaml:"public_url" json:"publicUrl"`
	TLSConfig *TLSConfig `yaml:"tls_config" json:"tlsConfig"`

	ShutdownWaitTime *time.Duration `yaml:"shutdown_wait_time" json:"shutdownWaitTime"`
}

HTTPConfig contains options for HTTP servers. It is usually embedded in a larger configuration struct.

func (*HTTPConfig) SetValuesFromEnv added in v0.2.1

func (c *HTTPConfig) SetValuesFromEnv(prefix string)

SetValuesFromEnv sets values in the configuration from corresponding environment variables, if they exist. The optional prefix is added to the start of the environment variable names.

type LoggingConfig

type LoggingConfig struct {
	Level string `yaml:"level" json:"level"`

	// Pretty will make the output human-readable
	Pretty bool `yaml:"pretty" json:"pretty"`
}

LoggingConfig contains options for logging, such as log level and textual representation. It is usually embedded in a larger configuration struct.

func (*LoggingConfig) SetValuesFromEnv added in v0.2.1

func (c *LoggingConfig) SetValuesFromEnv(prefix string)

SetValuesFromEnv sets values in the configuration from corresponding environment variables, if they exist. The optional prefix is added to the start of the environment variable names.

type Param

type Param func(b *Server) error

Param configures a Server instance.

func DefaultParams

func DefaultParams(logger zerolog.Logger, metricsPrefix string) []Param

DefaultParams returns a recommended set of parameters for servers. It enables logging and configures logging, adds metrics, and adds default middleware. All component parameters are exported and can be selected individually if desired.

func WithErrorLogging

func WithErrorLogging(marshalFunc func(err error) interface{}) Param

WithErrorLogging sets a formatting function used to log errors.

func WithHTTPServer

func WithHTTPServer(server *http.Server) Param

func WithLogger

func WithLogger(logger zerolog.Logger) Param

WithLogger sets a root logger used by the server.

func WithMetrics

func WithMetrics() Param

WithMetrics enables server and runtime metrics collection.

func WithMiddleware

func WithMiddleware(middleware ...func(http.Handler) http.Handler) Param

WithMiddleware sets middleware that is applied to all routes handled by the server.

func WithRegistry

func WithRegistry(registry metrics.Registry) Param

WithRegistry sets the metrics registry for the server.

func WithUTCNanoTime

func WithUTCNanoTime() Param

WithUTCNanoTime adds a UTC timestamp with nanosecond precision to log lines.

type RecordingResponseWriter added in v0.2.0

type RecordingResponseWriter interface {
	http.ResponseWriter

	// Status returns the HTTP status of the request, or 0 if one has not
	// yet been sent.
	Status() int

	// BytesWritten returns the total number of bytes sent to the client.
	BytesWritten() int64
}

RecordingResponseWriter is a proxy for an http.ResponseWriter that counts bytes written and http status send to the underlying ResponseWriter.

func WrapWriter added in v0.2.0

type Server

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

Server is the base server type. It is usually embedded in an application-specific struct.

func NewServer

func NewServer(c HTTPConfig, params ...Param) (*Server, error)

NewServer creates a Server instance from configuration and parameters.

func (*Server) HTTPConfig

func (s *Server) HTTPConfig() HTTPConfig

HTTPConfig returns the server configuration.

func (*Server) HTTPServer

func (s *Server) HTTPServer() *http.Server

HTTPServer returns the underlying HTTP Server.

func (*Server) Logger

func (s *Server) Logger() zerolog.Logger

Logger returns the root logger for the server.

func (*Server) Mux

func (s *Server) Mux() *goji.Mux

Mux returns the root mux for the server.

func (*Server) Registry

func (s *Server) Registry() metrics.Registry

Registry returns the root metrics registry for the server.

func (*Server) Start

func (s *Server) Start() error

Start starts the server and blocks.

type TLSConfig

type TLSConfig struct {
	CertFile string `yaml:"cert_file" json:"certFile"`
	KeyFile  string `yaml:"key_file" json:"keyFile"`
}

Directories

Path Synopsis
auth
oauth2
Package oauth2 implements an http.Handler that performs the 3-leg OAuth2 authentication flow.
Package oauth2 implements an http.Handler that performs the 3-leg OAuth2 authentication flow.
saml
Package saml provides the necessary handlers to implement a SAML authentication workflow.
Package saml provides the necessary handlers to implement a SAML authentication workflow.
Package datadog defines configuration and functions for emitting metrics to Datadog using the DogStatd protocol.
Package datadog defines configuration and functions for emitting metrics to Datadog using the DogStatd protocol.

Jump to

Keyboard shortcuts

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