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
- func AccessHandler(f AccessCallback) func(next http.Handler) http.Handler
- func CountRequest(r *http.Request, status int, _ int64, _ time.Duration)
- func DefaultMiddleware(logger zerolog.Logger, registry metrics.Registry) []func(http.Handler) http.Handler
- func HandleRouteError(w http.ResponseWriter, r *http.Request, err error)
- func LogRequest(r *http.Request, status int, size int64, elapsed time.Duration)
- func MetricsCtx(ctx context.Context) metrics.Registry
- func NewLogger(c LoggingConfig) zerolog.Logger
- func NewMetricsHandler(registry metrics.Registry) func(http.Handler) http.Handler
- func RecordRequest(r *http.Request, status int, size int64, elapsed time.Duration)
- func RegisterDefaultMetrics(registry metrics.Registry)
- func RichErrorMarshalFunc(err error) interface{}
- func WithMetricsCtx(ctx context.Context, registry metrics.Registry) context.Context
- func WriteJSON(w http.ResponseWriter, status int, obj interface{})
- type AccessCallback
- type HTTPConfig
- type LoggingConfig
- type Param
- func DefaultParams(logger zerolog.Logger, metricsPrefix string) []Param
- func WithErrorLogging(marshalFunc func(err error) interface{}) Param
- func WithHTTPServer(server *http.Server) Param
- func WithLogger(logger zerolog.Logger) Param
- func WithMetrics() Param
- func WithMiddleware(middleware ...func(http.Handler) http.Handler) Param
- func WithRegistry(registry metrics.Registry) Param
- func WithUTCNanoTime() Param
- type RecordingResponseWriter
- type Server
- type TLSConfig
Constants ¶
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 ¶
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 ¶
LogRequest is an AccessCallback that logs request information.
func MetricsCtx ¶
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 ¶
NewMetricsHandler returns middleware that add the given metrics registry to the request context.
func RecordRequest ¶
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 ¶
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 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 ¶
Param configures a Server instance.
func DefaultParams ¶
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 ¶
WithErrorLogging sets a formatting function used to log errors.
func WithHTTPServer ¶
func WithLogger ¶
WithLogger sets a root logger used by the server.
func WithMetrics ¶
func WithMetrics() Param
WithMetrics enables server and runtime metrics collection.
func WithMiddleware ¶
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
func WrapWriter(w http.ResponseWriter) RecordingResponseWriter
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 ¶
HTTPServer returns the underlying HTTP Server.
Source Files
¶
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. |