Documentation
¶
Overview ¶
Package core implements some core utilities
Index ¶
- Constants
- func ContainsString(slice []string, s string) bool
- func DefaultAppName() string
- func GetAppName(ctx context.Context) string
- func GetCurrentTime(ctx context.Context) time.Time
- func GetLogger(ctx context.Context) *logrus.Entry
- func GetRandFloat64(ctx context.Context) float64
- func GetRandIntn(ctx context.Context, n int) int
- func GetRandomBytes(ctx context.Context, n int) []byte
- func HTTPAddAdminRoute(ctx context.Context, r *mux.Router)
- func HTTPAddHealthRoute(ctx context.Context, r *mux.Router)
- func HTTPAddMetricsRoute(_ context.Context, r *mux.Router)
- func HTTPAddVersionRoute(ctx context.Context, r *mux.Router)
- func HTTPAdminHandler(ctx context.Context) http.Handler
- func HTTPHealthHandler(_ context.Context) http.Handler
- func HTTPVersionHandler(_ context.Context) http.Handler
- func NewDefaultContext(parent context.Context) context.Context
- func NewHTTPMiddleware(ctx context.Context, opts ...HTTPMiddlewareOption) []mux.MiddlewareFunc
- func RemoveString(slice []string, s string) (result []string)
- func SetDefaultLogLevel(l logrus.Level)
- func SetLevel(entry *logrus.Entry, level string) error
- func WithAppName(parent context.Context, appName string) context.Context
- func WithClock(parent context.Context, clockFunc func() time.Time) context.Context
- func WithDefaultLogger(parent context.Context) context.Context
- func WithLogger(parent context.Context, entry *logrus.Entry) context.Context
- func WithRandomSeed(parent context.Context, seed int64) context.Context
- func WithSignalHandler(parent context.Context) context.Context
- func WithTestingLogger(parent context.Context) (context.Context, *test.Hook)
- type HTTPMiddlewareOption
- type HTTPService
- func (s *HTTPService) AddAdminRoute(ctx context.Context)
- func (s *HTTPService) AddHealthRoute(ctx context.Context)
- func (s *HTTPService) AddMetricsRoute(ctx context.Context)
- func (s *HTTPService) AddVersionRoute(ctx context.Context)
- func (s *HTTPService) Done() <-chan struct{}
- func (s *HTTPService) Start(ctx context.Context) (net.Listener, error)
- type Rand
Constants ¶
const DefaultShutDownGracePeriod = 3 * time.Second
DefaultShutDownGracePeriod bounds `http.Server.Shutdown` for the services the constructors below create. The command that owns their lifecycle waits this long for them to drain before it flushes traces, and the deployments give the pod five seconds in total, so both budgets must stay inside that.
const MetricsNamespaceEnv = "METRICS_NAMESPACE"
MetricsNamespaceEnv overrides the prefix a caller passes to WithRequestMetrics. These services read no config file, so an environment variable is the only override available to an operator.
Variables ¶
This section is empty.
Functions ¶
func ContainsString ¶
ContainsString is a helper function
func DefaultAppName ¶
func DefaultAppName() string
DefaultAppName gets the name of the current executable
func GetAppName ¶
GetAppName fetches the appname key value
func GetCurrentTime ¶
GetCurrentTime returns the current time from the context or default
func GetRandFloat64 ¶
GetRandFloat64 returns a random float64
func GetRandIntn ¶
GetRandIntn returns a random int
func GetRandomBytes ¶
GetRandomBytes returns n random bytes
func HTTPAddAdminRoute ¶
HTTPAddAdminRoute adds the admin route
func HTTPAddHealthRoute ¶
HTTPAddHealthRoute adds a health route
func HTTPAddMetricsRoute ¶
HTTPAddMetricsRoute adds a metric route
func HTTPAddVersionRoute ¶
HTTPAddVersionRoute adds a version route
func HTTPAdminHandler ¶
HTTPAdminHandler provides debugging utilities. It should usually listen to 127.0.0.1 instead of exposing publicly (unless authNed and authZed). Currently admin handler allows update logging level while application is running, e.g.:
func HTTPHealthHandler ¶
HTTPHealthHandler handles the health ep
func HTTPVersionHandler ¶
HTTPVersionHandler handles the version ep
func NewDefaultContext ¶
NewDefaultContext provides a default context for applications.
func NewHTTPMiddleware ¶
func NewHTTPMiddleware(ctx context.Context, opts ...HTTPMiddlewareOption) []mux.MiddlewareFunc
NewHTTPMiddleware builds a http middleware that:
Adds contexted request logger with {method,path,ip} into request.Context
Collects <latencyMetricsName>_http_duration_seconds metrics with {path,method} dimensions, if latencyMetricsName is specified
- Wraps handler with http.TimeoutHandler with `handlerTimeout`.
- Wraps request.Body with MaxBytesReader with `requestBodyLimit`.
- Instruments OpenTelemetry by adding a span to the request context that tracks the response and its return codes
func RemoveString ¶
RemoveString is a helper function
func SetDefaultLogLevel ¶
SetDefaultLogLevel sets the default log level
func WithAppName ¶
WithAppName returns a context with the specified app name
func WithDefaultLogger ¶
WithDefaultLogger returns a context with the default logger
func WithLogger ¶
WithLogger gets a context with the logger
func WithRandomSeed ¶
WithRandomSeed sets a seed
func WithSignalHandler ¶
WithSignalHandler returns a context with signal handlers
Types ¶
type HTTPMiddlewareOption ¶
type HTTPMiddlewareOption func(*httpMiddleware)
HTTPMiddlewareOption defines a middleware option
func WithHandlerTimeout ¶
func WithHandlerTimeout(t time.Duration) HTTPMiddlewareOption
WithHandlerTimeout allows one to modify the handler timeout. Default is 5 seconds.
func WithRequestBodyLimit ¶
func WithRequestBodyLimit(limit int64) HTTPMiddlewareOption
WithRequestBodyLimit modifies the request body limit. Default is 1MB.
func WithRequestMetrics ¶
func WithRequestMetrics(serverName string) HTTPMiddlewareOption
WithRequestMetrics enables service specific metrics regarding request duration and count. By default these metrics are disabled. serverName is the prefix applied to the metric names, and METRICS_NAMESPACE takes precedence over it when set.
func WithTelemetry ¶
func WithTelemetry(serverName string) HTTPMiddlewareOption
WithTelemetry enables telemetry sets the http
type HTTPService ¶
type HTTPService struct {
*mux.Router
// Addr could be a TCP address like:
//
// - 0.0.0.0:8000 (any interface, port 8000)
// - 127.0.0.1:8000 (loop-back interface only, port 8000)
// - 0.0.0.0:0 (any interface, any free port)
//
// Addr could also be prefix with `unix://` (e.g.,
// `unix:///tmp/test.sock`), which will make HTTPService listen to a
// local unix domain socket instead of a network interface.
Addr string
// SocketPermission is only applicable when addr is a unix socket
// path, e.g., 'unix:///tmp/test.sock'
SocketPermission os.FileMode
// ReadTimeout, WriteTimeout and IdleTimeout are timeout
// configurations passed to go http.Server.
ReadTimeout, WriteTimeout, IdleTimeout time.Duration
// ShutDownGracePeriod is the grace period for
// `http.Server:Shutdown`
ShutDownGracePeriod time.Duration
// CertFile, KeyFile are used if TLS is required.
// They point to the corresponding files.
CertFile, KeyFile string
// contains filtered or unexported fields
}
HTTPService augments mux.Router with:
- Reasonable defaults
Helper methods for adding common routes (/healthz, /version, /metrics, /admin ...).
Handle both tcp addresses (e.g., :8000) and unix socket addresses (e.g., unix:///tmp/test.sock)
A non-blocking Start(ctx) method handles grace shutdown when receiving ctx.Done().
func NewHTTPService ¶
func NewHTTPService(addr string) *HTTPService
NewHTTPService creates a new service
func NewTLSService ¶
func NewTLSService(addr, certFile, keyFile string) *HTTPService
NewTLSService creates a new TLS service
func (*HTTPService) AddAdminRoute ¶
func (s *HTTPService) AddAdminRoute(ctx context.Context)
AddAdminRoute adds an admin route
func (*HTTPService) AddHealthRoute ¶
func (s *HTTPService) AddHealthRoute(ctx context.Context)
AddHealthRoute adds a health route
func (*HTTPService) AddMetricsRoute ¶
func (s *HTTPService) AddMetricsRoute(ctx context.Context)
AddMetricsRoute adds a metrics route
func (*HTTPService) AddVersionRoute ¶
func (s *HTTPService) AddVersionRoute(ctx context.Context)
AddVersionRoute adds a version route
func (*HTTPService) Done ¶
func (s *HTTPService) Done() <-chan struct{}
Done returns a channel closed once the service has stopped serving, either drained by Shutdown or closed after ShutDownGracePeriod. It is nil until Start is called.
type Rand ¶
Rand wraps *rand.Rand, provides thread-safe access to a subset of methods.
func (*Rand) RandomBytes ¶
RandomBytes returns n random bytes.