core

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2026 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Overview

Package core implements some core utilities

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ContainsString

func ContainsString(slice []string, s string) bool

ContainsString is a helper function

func DefaultAppName

func DefaultAppName() string

DefaultAppName gets the name of the current executable

func GetAppName

func GetAppName(ctx context.Context) string

GetAppName fetches the appname key value

func GetCurrentTime

func GetCurrentTime(ctx context.Context) time.Time

GetCurrentTime returns the current time from the context or default

func GetLogger

func GetLogger(ctx context.Context) *logrus.Entry

GetLogger gets a logger

func GetRandFloat64

func GetRandFloat64(ctx context.Context) float64

GetRandFloat64 returns a random float64

func GetRandIntn

func GetRandIntn(ctx context.Context, n int) int

GetRandIntn returns a random int

func GetRandomBytes

func GetRandomBytes(ctx context.Context, n int) []byte

GetRandomBytes returns n random bytes

func HTTPAddAdminRoute

func HTTPAddAdminRoute(ctx context.Context, r *mux.Router)

HTTPAddAdminRoute adds the admin route

func HTTPAddHealthRoute

func HTTPAddHealthRoute(ctx context.Context, r *mux.Router)

HTTPAddHealthRoute adds a health route

func HTTPAddMetricsRoute

func HTTPAddMetricsRoute(_ context.Context, r *mux.Router)

HTTPAddMetricsRoute adds a metric route

func HTTPAddVersionRoute

func HTTPAddVersionRoute(ctx context.Context, r *mux.Router)

HTTPAddVersionRoute adds a version route

func HTTPAdminHandler

func HTTPAdminHandler(ctx context.Context) http.Handler

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.:

curl http://127.0.0.1:8002/admin?log-level=debug

func HTTPHealthHandler

func HTTPHealthHandler(_ context.Context) http.Handler

HTTPHealthHandler handles the health ep

func HTTPVersionHandler

func HTTPVersionHandler(_ context.Context) http.Handler

HTTPVersionHandler handles the version ep

func NewDefaultContext

func NewDefaultContext(parent context.Context) context.Context

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

func RemoveString(slice []string, s string) (result []string)

RemoveString is a helper function

func SetDefaultLogLevel

func SetDefaultLogLevel(l logrus.Level)

SetDefaultLogLevel sets the default log level

func SetLevel

func SetLevel(entry *logrus.Entry, level string) error

SetLevel sets the log level

func StartOTELDaemon

func StartOTELDaemon(ctx context.Context)

StartOTELDaemon starts a go routine that waits on the provided context to quit and then shuts down the daemon

func WithAppName

func WithAppName(parent context.Context, appName string) context.Context

WithAppName returns a context with the specified app name

func WithClock

func WithClock(parent context.Context, clockFunc func() time.Time) context.Context

WithClock gets a context with a clock func

func WithDefaultLogger

func WithDefaultLogger(parent context.Context) context.Context

WithDefaultLogger returns a context with the default logger

func WithLogger

func WithLogger(parent context.Context, entry *logrus.Entry) context.Context

WithLogger gets a context with the logger

func WithRandomSeed

func WithRandomSeed(parent context.Context, seed int64) context.Context

WithRandomSeed sets a seed

func WithSignalHandler

func WithSignalHandler(parent context.Context) context.Context

WithSignalHandler returns a context with signal handlers

func WithTestingLogger

func WithTestingLogger(parent context.Context) (context.Context, *test.Hook)

WithTestingLogger gets a context with test hook

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.

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

func (s *HTTPService) Start(ctx context.Context) (net.Listener, error)

Start starts the service

type Rand

type Rand struct {
	sync.Mutex
	*rand.Rand
}

Rand wraps *rand.Rand, provides thread-safe access to a subset of methods.

func (*Rand) Float64

func (r *Rand) Float64() float64

Float64 returns a random float64

func (*Rand) Intn

func (r *Rand) Intn(n int) int

Intn returns a random int

func (*Rand) RandomBytes

func (r *Rand) RandomBytes(n int) []byte

RandomBytes returns n random bytes.

Jump to

Keyboard shortcuts

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