server

package
Version: v1.3.6 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2020 License: Apache-2.0 Imports: 30 Imported by: 331

Documentation

Overview

Package server is the bulk of the toolkit and relies on `server.Config` to manage `Server` implementations.

Index

Constants

View Source
const JSONContentType = "application/json; charset=UTF-8"

JSONContentType can be used for setting the Content-Type header for JSON encoding.

Variables

View Source
var (
	// ErrMultiRegister occurs when a Register method is called multiple times
	ErrMultiRegister = errors.New("register method has been called multiple times")

	// Name is used for status and logging.
	Name = "nyt-awesome-go-server"
	// Log is the global logger for the server. It will take care of logrotate
	// and it can accept 'fields' to include with each log line: see LogWithFields(r).
	Log = logrus.New()
)
View Source
var UnexpectedServerError = []byte("unexpected server error")

UnexpectedServerError is returned with a 500 status code when SimpleServer recovers from a panic in a request.

View Source
var Version string

Version is meant to be set with the current package version at build time.

Functions

func AddIPToContext

func AddIPToContext(r *http.Request)

AddIPToContext will attempt to pull an IP address out of the request and set it into a gorilla context.

func CORSHandler

func CORSHandler(f http.Handler, originSuffix string) http.Handler

CORSHandler is a middleware func for setting all headers that enable CORS. If an originSuffix is provided, a strings.HasSuffix check will be performed before adding any CORS header. If an empty string is provided, any Origin header found will be placed into the CORS header. If no Origin header is found, no headers will be added.

func ContextFields

func ContextFields(r *http.Request) map[string]interface{}

ContextFields will take a request and convert a context map to logrus Fields.

func ContextToHTTP

func ContextToHTTP(ep ContextHandler) http.Handler

ContextToHTTP is a middleware func to convert a ContextHandler an http.Handler.

func ContextWithForwardForIP

func ContextWithForwardForIP(ctx netContext.Context, r *http.Request) netContext.Context

ContextWithForwardForIP returns new context with forward for ip.

func ContextWithUserIP

func ContextWithUserIP(ctx netContext.Context, r *http.Request) netContext.Context

ContextWithUserIP returns new context with user ip address.

func GetForwardedIP

func GetForwardedIP(r *http.Request) string

GetForwardedIP returns the "X-Forwarded-For" header value.

func GetIP

func GetIP(r *http.Request) (string, error)

GetIP returns the IP address for the given request.

func GetInt64Var added in v0.4.0

func GetInt64Var(r *http.Request, key string) int64

GetInt64Var is a helper to pull gorilla mux Vars. If the value is empty, it falls back to the URL query string. We are ignoring the error here bc we're assuming the path had a [0-9]+ descriptor on this var.

func GetUInt64Var added in v0.4.0

func GetUInt64Var(r *http.Request, key string) uint64

GetUInt64Var is a helper to pull gorilla mux Vars. If the value is empty, it falls back to the URL query string. We are ignoring the error here bc we're assuming the path had a [0-9]+ descriptor on this var.

func Init

func Init(name string, scfg *Config)

Init will set up our name, logging, healthchecks and parse flags. If DefaultServer isn't set, this func will set it to a `SimpleServer` listening on `Config.HTTPPort`.

func JSONPHandler

func JSONPHandler(f http.Handler) http.Handler

JSONPHandler is a middleware func for wrapping response body with JSONP.

func JSONToHTTP

func JSONToHTTP(ep JSONEndpoint) http.Handler

JSONToHTTP is the middleware func to convert a JSONEndpoint to an http.HandlerFunc.

func LogWithFields

func LogWithFields(r *http.Request) *logrus.Entry

LogWithFields will feed any request context into a logrus Entry.

func MetricsNamespace

func MetricsNamespace() string

MetricsNamespace returns "apps.{hostname prefix}", which is the convention used in NYT ESX environment.

func NewAccessLogMiddleware

func NewAccessLogMiddleware(logLocation *string, handler http.Handler) (http.Handler, error)

NewAccessLogMiddleware will wrap a logrotate-aware Apache-style access log handler around the given http.Handler if an access log location is provided by the config, or optionally send access logs to stdout.

func NoCacheHandler

func NoCacheHandler(f http.Handler) http.Handler

NoCacheHandler is a middleware func for setting the Cache-Control to no-cache.

func ParseTruthyFalsy added in v0.4.0

func ParseTruthyFalsy(flag interface{}) (result bool, err error)

ParseTruthyFalsy is a helper method to attempt to parse booleans in APIs that have no set contract on what a boolean should look like.

func Register

func Register(svc Service) error

Register will add a new Service to the DefaultServer.

func RegisterProfiler

func RegisterProfiler(cfg *Config, mx Router)

RegisterProfiler will add handlers for pprof endpoints if the config has them enabled.

func Run

func Run() error

Run will start the DefaultServer and set it up to Stop() on a kill signal.

func SetConfigOverrides

func SetConfigOverrides(c *Config)

SetConfigOverrides will check the *CLI variables for any values and override the values in the given config if they are set. If LogCLI is set to "dev", the given `Log` pointer will be set to an empty string.

func SetLogLevel

func SetLogLevel(scfg *Config)

SetLogLevel will set the appropriate logrus log level given the server config.

func SetRouteVars added in v0.4.0

func SetRouteVars(r *http.Request, val interface{})

SetRouteVars will set the given value into into the request context with the shared 'vars' storage key.

func Stop

func Stop() error

Stop will stop the default server.

func Vars added in v0.4.0

func Vars(r *http.Request) map[string]string

Vars is a helper function for accessing route parameters from any server.Router implementation. This is the equivalent of using `mux.Vars(r)` with the Gorilla mux.Router.

Types

type ActivityMonitor

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

ActivityMonitor can be used to count and share the number of active requests.

func NewActivityMonitor

func NewActivityMonitor() *ActivityMonitor

NewActivityMonitor will return a new ActivityMonitor instance.

func (*ActivityMonitor) Active

func (a *ActivityMonitor) Active() bool

Active returns true if there are requests currently in flight.

func (*ActivityMonitor) CountRequest

func (a *ActivityMonitor) CountRequest()

CountRequest will increment the request count and signal the activity monitor to stay active. Call this in your server when you receive a request.

func (*ActivityMonitor) NumActiveRequests

func (a *ActivityMonitor) NumActiveRequests() uint32

NumActiveRequests returns the number of in-flight requests currently running on this server.

func (*ActivityMonitor) UncountRequest

func (a *ActivityMonitor) UncountRequest()

UncountRequest will decrement the active request count. Best practice is to `defer` this function call directly after calling CountRequest().

type Config

type Config struct {
	// HealthCheckType is used by server to init the proper HealthCheckHandler.
	// If empty, this will default to 'simple'.
	HealthCheckType string `envconfig:"GIZMO_HEALTH_CHECK_TYPE"`
	// HealthCheckPath is used by server to init the proper HealthCheckHandler.
	// If empty, this will default to '/status.txt'.
	HealthCheckPath string `envconfig:"GIZMO_HEALTH_CHECK_PATH"`
	// CustomHealthCheckHandler will be used if HealthCheckType is set with "custom".
	CustomHealthCheckHandler http.Handler

	// RouterType is used by the server to init the proper Router implementation.
	// The current available types are 'gorilla' to use the Gorilla tool kit mux and
	// 'stdlib' to use the http package's ServeMux.
	// If empty, this will default to 'gorilla'.
	// NOTE: If 'stdlib' is used, Prometheus monitoring will be disabled for performance
	// reasons.
	RouterType string `envconfig:"GIZMO_ROUTER_TYPE"`

	// JSONContentType can be used to override the default JSONContentType.
	JSONContentType *string `envconfig:"GIZMO_JSON_CONTENT_TYPE"`
	// MaxHeaderBytes can be used to override the default MaxHeaderBytes (1<<20).
	MaxHeaderBytes *int `envconfig:"GIZMO_MAX_HEADER_BYTES"`
	// ReadTimeout can be used to override the default http server timeout of 10s.
	// The string should be formatted like a time.Duration string.
	ReadTimeout *string `envconfig:"GIZMO_READ_TIMEOUT"`
	// WriteTimeout can be used to override the default http server timeout of 10s.
	// The string should be formatted like a time.Duration string.
	WriteTimeout *string `envconfig:"GIZMO_WRITE_TIMEOUT"`
	// IdleTimeout can be used to override the default http server timeout of 120s.
	// The string should be formatted like a time.Duration string. This
	// feature is supported only on Go 1.8+.
	IdleTimeout *string `envconfig:"GIZMO_IDLE_TIMEOUT"`

	// GOMAXPROCS can be used to override the default GOMAXPROCS (runtime.NumCPU).
	GOMAXPROCS *int `envconfig:"GIZMO_SERVER_GOMAXPROCS"`

	// HTTPAccessLog is the location of the http access log. If it is empty,
	// no access logging will be done.
	HTTPAccessLog *string `envconfig:"HTTP_ACCESS_LOG"`
	// RPCAccessLog is the location of the RPC access log. If it is empty,
	// no access logging will be done.
	RPCAccessLog *string `envconfig:"RPC_ACCESS_LOG"`

	// HTTPAddr is the address the server implementation will bind to.
	HTTPAddr string `envconfig:"HTTP_ADDR"`
	// HTTPPort is the port the server implementation will serve HTTP over.
	HTTPPort int `envconfig:"HTTP_PORT"`
	// RPCPort is the port the server implementation will serve RPC over.
	RPCPort int `envconfig:"RPC_PORT"`

	// Log is the path to the application log.
	Log string `envconfig:"APP_LOG"`
	// LogLevel will override the default log level of 'info'.
	LogLevel string `envconfig:"APP_LOG_LEVEL"`
	// LogJSONFormat will override the default JSON formatting logic on the server.
	// By default the Server will log in a JSON format only if the Log field
	// is defined.
	// If this field is set and true, the logrus JSONFormatter will be used.
	LogJSONFormat *bool `envconfig:"APP_LOG_JSON_FMT"`

	// TLSCertFile is an optional string for enabling TLS in simple servers.
	TLSCertFile *string `envconfig:"TLS_CERT"`
	// TLSKeyFile is an optional string for enabling TLS in simple servers.
	TLSKeyFile *string `envconfig:"TLS_KEY"`

	// NotFoundHandler will override the default server NotfoundHandler if set.
	NotFoundHandler http.Handler

	// Enable pprof Profiling. Off by default.
	EnablePProf bool `envconfig:"ENABLE_PPROF"`

	// MetricsNamespace is used by prometheus.
	MetricsNamespace string `envconfig:"METRICS_NAMESPACE"`
	// MetricsSubsystem is used by prometheus.
	MetricsSubsystem string `envconfig:"METRICS_SUBSYSTEM"`
	// MetricsPath is where the prometheus endpoint will be registered.
	MetricsPath string `envconfig:"METRICS_PATH"`
}

Config holds info required to configure a gizmo server.Server.

func LoadConfigFromEnv

func LoadConfigFromEnv() *Config

LoadConfigFromEnv will attempt to load a Server object from environment variables. If not populated, nil is returned.

type ContextHandler

type ContextHandler interface {
	ServeHTTPContext(context.Context, http.ResponseWriter, *http.Request)
}

ContextHandler is an equivalent to http.Handler but with additional param.

func JSONContextToHTTP

func JSONContextToHTTP(ep JSONContextEndpoint) ContextHandler

JSONContextToHTTP is a middleware func to convert a ContextHandler an http.Handler.

func WithCloseHandler

func WithCloseHandler(h ContextHandler) ContextHandler

WithCloseHandler returns a Handler cancelling the context when the client connection close unexpectedly.

type ContextHandlerFunc

type ContextHandlerFunc func(context.Context, http.ResponseWriter, *http.Request)

ContextHandlerFunc is an equivalent to SimpleService's http.HandlerFunc.

func (ContextHandlerFunc) ServeHTTPContext

func (h ContextHandlerFunc) ServeHTTPContext(ctx context.Context, rw http.ResponseWriter, req *http.Request)

ServeHTTPContext is an implementation of ContextHandler interface.

type ContextKey

type ContextKey int

ContextKey used to create context keys.

const (
	// UserIPKey is key to set/retrieve value from context.
	UserIPKey ContextKey = 0

	// UserForwardForIPKey is key to set/retrieve value from context.
	UserForwardForIPKey ContextKey = 1
)

type ContextService

type ContextService interface {
	Service

	// route - method - func
	ContextEndpoints() map[string]map[string]ContextHandlerFunc
	ContextMiddleware(ContextHandler) ContextHandler
}

ContextService is an interface defining a service that is made up of ContextHandlerFuncs.

type CustomHealthCheck

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

CustomHealthCheck is a HealthCheckHandler that uses a custom http.Handler provided to the server via `config.CustomHealthCheckHandler`.

func NewCustomHealthCheck

func NewCustomHealthCheck(path string, handler http.Handler) *CustomHealthCheck

NewCustomHealthCheck will return a new CustomHealthCheck with the given path and handler.

func (*CustomHealthCheck) Path

func (c *CustomHealthCheck) Path() string

Path will return the configured status path to server on.

func (*CustomHealthCheck) ServeHTTP

func (c *CustomHealthCheck) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP will allow the custom handler to manage the request and response.

func (*CustomHealthCheck) Start

func (c *CustomHealthCheck) Start(monitor *ActivityMonitor) error

Start will do nothing.

func (*CustomHealthCheck) Stop

func (c *CustomHealthCheck) Stop() error

Stop will do nothing and return nil.

type GorillaRouter

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

GorillaRouter is a Router implementation for the Gorilla web toolkit's `mux.Router`.

func (*GorillaRouter) Handle

func (g *GorillaRouter) Handle(method, path string, h http.Handler)

Handle will call the Gorilla web toolkit's Handle().Method() methods.

func (*GorillaRouter) HandleFunc

func (g *GorillaRouter) HandleFunc(method, path string, h func(http.ResponseWriter, *http.Request))

HandleFunc will call the Gorilla web toolkit's HandleFunc().Method() methods.

func (*GorillaRouter) ServeHTTP

func (g *GorillaRouter) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP will call Gorilla mux.Router.ServerHTTP directly.

func (*GorillaRouter) SetNotFoundHandler

func (g *GorillaRouter) SetNotFoundHandler(h http.Handler)

SetNotFoundHandler will set the Gorilla mux.Router.NotFoundHandler.

type HealthCheckHandler

type HealthCheckHandler interface {
	http.Handler
	Path() string
	Start(*ActivityMonitor) error
	Stop() error
}

HealthCheckHandler is an interface used by SimpleServer and RPCServer to allow users to customize their service's health check. Start will be called just before server start up and the given ActivityMonitor should offer insite to the # of requests in flight, if needed. Stop will be called once the servers receive a kill signal.

func NewHealthCheckHandler

func NewHealthCheckHandler(cfg *Config) (HealthCheckHandler, error)

NewHealthCheckHandler will inspect the config to generate the appropriate HealthCheckHandler.

func RegisterHealthHandler

func RegisterHealthHandler(cfg *Config, monitor *ActivityMonitor, mx Router) HealthCheckHandler

RegisterHealthHandler will create a new HealthCheckHandler from the given config and add a handler to the given router.

type JSONContextEndpoint

type JSONContextEndpoint func(context.Context, *http.Request) (int, interface{}, error)

JSONContextEndpoint is the JSONContextService equivalent to JSONService's JSONEndpoint.

type JSONEndpoint

type JSONEndpoint func(*http.Request) (int, interface{}, error)

JSONEndpoint is the JSONService equivalent to SimpleService's http.HandlerFunc.

type JSONService

type JSONService interface {
	Service

	// Ensure that the route syntax is compatible with the router
	// implementation chosen in cfg.RouterType.
	// route - method - func
	JSONEndpoints() map[string]map[string]JSONEndpoint
	JSONMiddleware(JSONEndpoint) JSONEndpoint
}

JSONService is an interface defining a service that is made up of JSONEndpoints.

type MixedContextService

type MixedContextService interface {
	ContextService

	// route - method - func
	JSONEndpoints() map[string]map[string]JSONContextEndpoint
	JSONContextMiddleware(JSONContextEndpoint) JSONContextEndpoint
}

MixedContextService is an interface defining a service that is made up of JSONContextEndpoints and ContextHandlerFuncs.

type MixedService

type MixedService interface {
	Service

	// route - method - func
	Endpoints() map[string]map[string]http.HandlerFunc

	// Ensure that the route syntax is compatible with the router
	// implementation chosen in cfg.RouterType.
	// route - method - func
	JSONEndpoints() map[string]map[string]JSONEndpoint
	JSONMiddleware(JSONEndpoint) JSONEndpoint
}

MixedService is an interface defining service that offer JSONEndpoints and simple http.HandlerFunc endpoints.

type RPCService

type RPCService interface {
	ContextService

	Service() (*grpc.ServiceDesc, interface{})

	// Ensure that the route syntax is compatible with the router
	// implementation chosen in cfg.RouterType.
	// route - method - func
	JSONEndpoints() map[string]map[string]JSONContextEndpoint
	JSONMiddleware(JSONContextEndpoint) JSONContextEndpoint
}

RPCService is an interface defining an grpc-compatible service that also offers JSONContextEndpoints and ContextHandlerFuncs.

type Router

type Router interface {
	Handle(method string, path string, handler http.Handler)
	HandleFunc(method string, path string, handlerFunc func(http.ResponseWriter, *http.Request))
	ServeHTTP(w http.ResponseWriter, r *http.Request)
	SetNotFoundHandler(handler http.Handler)
}

Router is an interface to wrap different router types to be embedded within Gizmo server.Server implementations.

func NewRouter

func NewRouter(cfg *Config) Router

NewRouter will return the router specified by the server config. If no Router value is supplied, the server will default to using Gorilla mux.

type Server

type Server interface {
	Register(Service) error
	Start() error
	Stop() error
}

Server is the basic interface that defines what to expect from any server.

func NewServer

func NewServer(cfg *Config) Server

NewServer will inspect the config and generate the appropriate Server implementation.

type Service

type Service interface {
	Prefix() string

	// Middleware is a hook to enable services to add
	// any additional middleware.
	Middleware(http.Handler) http.Handler
}

Service is the most basic interface of a service that can be received and hosted by a Server.

type SimpleHealthCheck

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

SimpleHealthCheck is a basic HealthCheckHandler implementation that _always_ returns with an "ok" status and shuts down immediately.

func NewSimpleHealthCheck

func NewSimpleHealthCheck(path string) *SimpleHealthCheck

NewSimpleHealthCheck will return a new SimpleHealthCheck instance.

func (*SimpleHealthCheck) Path

func (s *SimpleHealthCheck) Path() string

Path will return the configured status path to server on.

func (*SimpleHealthCheck) ServeHTTP

func (s *SimpleHealthCheck) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP will always respond with "ok-"+server.Name.

func (*SimpleHealthCheck) Start

func (s *SimpleHealthCheck) Start(monitor *ActivityMonitor) error

Start will do nothing.

func (*SimpleHealthCheck) Stop

func (s *SimpleHealthCheck) Stop() error

Stop will do nothing and return nil.

type SimpleServer

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

SimpleServer is a basic http Server implementation for serving SimpleService, JSONService or MixedService implementations.

func NewSimpleServer

func NewSimpleServer(cfg *Config) *SimpleServer

NewSimpleServer will init the mux, exit channel and build the address from the given port. It will register the HealthCheckHandler at the given path and set up the shutDownHandler to be called on Stop().

func (*SimpleServer) Register

func (s *SimpleServer) Register(svcI Service) error

Register will accept and register SimpleServer, JSONService or MixedService implementations.

func (*SimpleServer) ServeHTTP

func (s *SimpleServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is SimpleServer's hook for metrics and safely executing each request.

func (*SimpleServer) Start

func (s *SimpleServer) Start() error

Start will start the SimpleServer at it's configured address. If they are configured, this will start health checks and access logging.

func (*SimpleServer) Stop

func (s *SimpleServer) Stop() error

Stop initiates the shutdown process and returns when the server completes.

type SimpleService

type SimpleService interface {
	Service

	// route - method - func
	Endpoints() map[string]map[string]http.HandlerFunc
}

SimpleService is an interface defining a service that is made up of http.HandlerFuncs.

type TCPKeepAliveListener

type TCPKeepAliveListener struct {
	*net.TCPListener
}

TCPKeepAliveListener sets TCP keep-alive timeouts on accepted connections. It's used by ListenAndServe and ListenAndServeTLS so dead TCP connections (e.g. closing laptop mid-download) eventually go away.

This is here because it is not exposed in the stdlib and we'd prefer to have a hold of the http.Server's net.Listener so we can close it on shutdown.

Taken from here: https://golang.org/src/net/http/server.go?s=63121:63175#L2120

func (TCPKeepAliveListener) Accept

func (ln TCPKeepAliveListener) Accept() (c net.Conn, err error)

Accept accepts the next incoming call and returns the new connection. KeepAlivePeriod is set properly.

Directories

Path Synopsis
Package kit implements an opinionated server based on go-kit primitives.
Package kit implements an opinionated server based on go-kit primitives.

Jump to

Keyboard shortcuts

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