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.
Example (IgnoreRequests) ¶
ignoreHandler := NewIgnoreHandler() printHandler := func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { next.ServeHTTP(w, r) fmt.Printf("%s - logs: %t\n", r.URL.Path, IsIgnored(r, IgnoreRule{Logs: true})) fmt.Printf("%s - metrics: %t\n", r.URL.Path, IsIgnored(r, IgnoreRule{Metrics: true})) }) } exampleHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/api/health" { Ignore(r, IgnoreRule{Logs: true}) } }) h := ignoreHandler(printHandler(exampleHandler)) r1 := httptest.NewRequest("GET", "/api/health", nil) w1 := httptest.NewRecorder() h.ServeHTTP(w1, r1) r2 := httptest.NewRequest("GET", "/api/auth/login", nil) w2 := httptest.NewRecorder() h.ServeHTTP(w2, r2)
Output: /api/health - logs: true /api/health - metrics: false /api/auth/login - logs: false /api/auth/login - metrics: false
Index ¶
- Constants
- func AccessHandler(f AccessCallback) func(next http.Handler) http.Handler
- func CountRequest(r *http.Request, status int, _ int64, elapsed 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 Ignore(r *http.Request, rule IgnoreRule)
- func IgnoreAll(r *http.Request)
- func IsIgnored(r *http.Request, rule IgnoreRule) bool
- func LogRequest(r *http.Request, status int, size int64, elapsed time.Duration)
- func MetricsCtx(ctx context.Context) metrics.Registry
- func NewIgnoreHandler() func(http.Handler) http.Handler
- 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 IgnoreRule
- 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
Examples ¶
Constants ¶
const ( MetricsKeyRequests = "server.requests" MetricsKeyRequests2xx = "server.requests.2xx" MetricsKeyRequests3xx = "server.requests.3xx" MetricsKeyRequests4xx = "server.requests.4xx" MetricsKeyRequests5xx = "server.requests.5xx" MetricsKeyLatencySuffix = ".latency" 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 requests, respecting ignore rules
- 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 Ignore ¶ added in v0.5.0
func Ignore(r *http.Request, rule IgnoreRule)
Ignore sets reporting to ignore for a request. Use this to disable logging or metrics for particular request types, like health checks. Call Ignore with an empty rule to re-enable reporting for a request that was previously ignored.
Ignore only works if the middleware returned by NewIgnoreHandler is used before the handler and before any reporting middleware in the middleware stack. If this middleware does not exist, Ignore has no effect.
func IgnoreAll ¶ added in v0.5.0
IgnoreAll is equivalent to calling Ignore with an IgnoreRule that ignores all possible reporting.
func IsIgnored ¶ added in v0.5.0
func IsIgnored(r *http.Request, rule IgnoreRule) bool
IsIgnored returns true if the request ignores all of the reporting types set in rule. The request may also ignore other reporting types not set in rule.
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 NewIgnoreHandler ¶ added in v0.5.0
NewIgnoreHandler returns middleware that tracks whether specific requests should be ignored in logs and metrics.
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 IgnoreRule ¶ added in v0.5.0
type IgnoreRule struct { // If true, do not log this request Logs bool // If true, do not report metrics for this request Metrics bool }
IgnoreRule specifies which types of reporting to ignore for a particular request.
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 re-exports appmetrics/emitter/datadog to preserve compatibility.
|
Package datadog re-exports appmetrics/emitter/datadog to preserve compatibility. |