...

Package baseapp

import "github.com/palantir/go-baseapp/baseapp"
Overview
Index
Subdirectories

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
    func (c *HTTPConfig) SetValuesFromEnv(prefix string)
type LoggingConfig
    func (c *LoggingConfig) SetValuesFromEnv(prefix string)
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
    func WrapWriter(w http.ResponseWriter) RecordingResponseWriter
type Server
    func NewServer(c HTTPConfig, params ...Param) (*Server, error)
    func (s *Server) HTTPConfig() HTTPConfig
    func (s *Server) HTTPServer() *http.Server
    func (s *Server) Logger() zerolog.Logger
    func (s *Server) Mux() *goji.Mux
    func (s *Server) Registry() metrics.Registry
    func (s *Server) Start() error
type TLSConfig

Package files

config.go doc.go error.go logging.go metrics.go middleware.go params.go recording_writer.go server.go

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"
)

func AccessHandler

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:

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.

type AccessCallback

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

type HTTPConfig

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

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"`
}

func (*HTTPConfig) SetValuesFromEnv

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

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

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

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

func (*LoggingConfig) SetValuesFromEnv

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.

type Param func(b *Server) error

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

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

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
}

func WrapWriter

func WrapWriter(w http.ResponseWriter) RecordingResponseWriter

type Server

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

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

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"`
}

Subdirectories

Name Synopsis
..
auth
oauth2 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.
datadog Package datadog defines configuration and functions for emitting metrics to Datadog using the DogStatd protocol.