gizmo: github.com/NYTimes/gizmo/server Index | Files | Directories

package server

import "github.com/NYTimes/gizmo/server"

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

Index

Package Files

activity.go config.go context_native.go doc.go func.go healthcheck.go http_server.go middleware.go router.go server.go service.go simple_server.go tcp.go vars_native.go

Constants

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

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

Variables

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()
)
var UnexpectedServerError = []byte("unexpected server error")

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

var Version string

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

func AddIPToContext Uses

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 Uses

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 Uses

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

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

func ContextToHTTP Uses

func ContextToHTTP(ep ContextHandler) http.Handler

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

func ContextWithForwardForIP Uses

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

ContextWithForwardForIP returns new context with forward for ip.

func ContextWithUserIP Uses

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

ContextWithUserIP returns new context with user ip address.

func GetForwardedIP Uses

func GetForwardedIP(r *http.Request) string

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

func GetIP Uses

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

GetIP returns the IP address for the given request.

func GetInt64Var Uses

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 Uses

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 Uses

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 Uses

func JSONPHandler(f http.Handler) http.Handler

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

func JSONToHTTP Uses

func JSONToHTTP(ep JSONEndpoint) http.Handler

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

func LogWithFields Uses

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

LogWithFields will feed any request context into a logrus Entry.

func MetricsNamespace Uses

func MetricsNamespace() string

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

func NewAccessLogMiddleware Uses

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 Uses

func NoCacheHandler(f http.Handler) http.Handler

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

func ParseTruthyFalsy Uses

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 Uses

func Register(svc Service) error

Register will add a new Service to the DefaultServer.

func RegisterProfiler Uses

func RegisterProfiler(cfg *Config, mx Router)

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

func Run Uses

func Run() error

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

func SetConfigOverrides Uses

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 Uses

func SetLogLevel(scfg *Config)

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

func SetRouteVars Uses

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 Uses

func Stop() error

Stop will stop the default server.

func Vars Uses

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.

type ActivityMonitor Uses

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

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

func NewActivityMonitor Uses

func NewActivityMonitor() *ActivityMonitor

NewActivityMonitor will return a new ActivityMonitor instance.

func (*ActivityMonitor) Active Uses

func (a *ActivityMonitor) Active() bool

Active returns true if there are requests currently in flight.

func (*ActivityMonitor) CountRequest Uses

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 Uses

func (a *ActivityMonitor) NumActiveRequests() uint32

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

func (*ActivityMonitor) UncountRequest Uses

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 Uses

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.
    // If empty, this will default to 'gorilla'.
    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_JSON_CONTENT_TYPE"`
    // 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"`

    // 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 Uses

func LoadConfigFromEnv() *Config

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

type ContextHandler Uses

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

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

func JSONContextToHTTP Uses

func JSONContextToHTTP(ep JSONContextEndpoint) ContextHandler

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

func WithCloseHandler Uses

func WithCloseHandler(h ContextHandler) ContextHandler

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

type ContextHandlerFunc Uses

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

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

func (ContextHandlerFunc) ServeHTTPContext Uses

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

ServeHTTPContext is an implementation of ContextHandler interface.

type ContextKey Uses

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 Uses

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 Uses

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 Uses

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

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

func (*CustomHealthCheck) Path Uses

func (c *CustomHealthCheck) Path() string

Path will return the configured status path to server on.

func (*CustomHealthCheck) ServeHTTP Uses

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 Uses

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

Start will do nothing.

func (*CustomHealthCheck) Stop Uses

func (c *CustomHealthCheck) Stop() error

Stop will do nothing and return nil.

type GorillaRouter Uses

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

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

func (*GorillaRouter) Handle Uses

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

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

func (*GorillaRouter) HandleFunc Uses

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 Uses

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

ServeHTTP will call Gorilla mux.Router.ServerHTTP directly.

func (*GorillaRouter) SetNotFoundHandler Uses

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

SetNotFoundHandler will set the Gorilla mux.Router.NotFoundHandler.

type HealthCheckHandler Uses

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 Uses

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

NewHealthCheckHandler will inspect the config to generate the appropriate HealthCheckHandler.

func RegisterHealthHandler Uses

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 Uses

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

JSONContextEndpoint is the JSONContextService equivalent to JSONService's JSONEndpoint.

type JSONEndpoint Uses

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

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

type JSONService Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

func NewServer(cfg *Config) Server

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

type Service Uses

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 Uses

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 Uses

func NewSimpleHealthCheck(path string) *SimpleHealthCheck

NewSimpleHealthCheck will return a new SimpleHealthCheck instance.

func (*SimpleHealthCheck) Path Uses

func (s *SimpleHealthCheck) Path() string

Path will return the configured status path to server on.

func (*SimpleHealthCheck) ServeHTTP Uses

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

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

func (*SimpleHealthCheck) Start Uses

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

Start will do nothing.

func (*SimpleHealthCheck) Stop Uses

func (s *SimpleHealthCheck) Stop() error

Stop will do nothing and return nil.

type SimpleServer Uses

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

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

func NewSimpleServer Uses

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 Uses

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

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

func (*SimpleServer) ServeHTTP Uses

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 Uses

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 Uses

func (s *SimpleServer) Stop() error

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

type SimpleService Uses

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 Uses

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 Uses

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

PathSynopsis
kitPackage kit implements an opinionated server based on go-kit primitives.

Package server imports 30 packages (graph) and is imported by 76 packages. Updated 2019-06-18. Refresh now. Tools for package owners.