Documentation
¶
Overview ¶
Package ctxval provides type-safe functions to set and get values from a context. Because the context needs to be used in http handlers to store the request-specific logger (i.e. a logger with the current request's ID in its fields), it makes sense to be pragmatic about it and also store the main top-level logger in the context in the application's main function. This top-level logger will be properly overridden by the request's logger in a child context.
For this reason, the ctxval package also provides helper functions to log an error and an information message using the logger stored in the context, if one is present.
The current execution environment is also stored in the context and should be set in the application's main function (typically read from an environment variable). Again, it is a pragmatic choice to have it available here as the context is passed around all layers, instead of having a global variable somewhere that all those layers read from.
Index ¶
- Variables
- func EnvIn(ctx context.Context, envs ...Environment) bool
- func LogErr(ctx context.Context, err error, msg string)
- func LogInfo(ctx context.Context, msg string)
- func Logger(ctx context.Context) (log.Logger, bool)
- func SetEnv(ctx context.Context, env Environment) context.Context
- func SetLogger(ctx context.Context, l log.Logger) context.Context
- type Environment
Constants ¶
This section is empty.
Variables ¶
var ValidEnvs = map[Environment]bool{ EnvLocal: true, EnvTest: true, EnvStaging: true, EnvProduction: true, }
ValidEnvs is the set of valid environments. An application can change that set in its main function before storing the current environment in the top-level context, if necessary.
Functions ¶
func EnvIn ¶
func EnvIn(ctx context.Context, envs ...Environment) bool
EnvIn returns true if the execution environment stored in ctx is any of envs. It returns false otherwise.
func LogErr ¶
LogErr is a helper function to log the provided error to the context logger if one is set.
func LogInfo ¶
LogInfo is a helper function to log the provided information message to the context logger if one is set.
func Logger ¶
Logger returns the logger stored in the context. If there is no logger in the context, it returns false as second value.
Types ¶
type Environment ¶
type Environment string
Environment indicates an execution environment.
const ( EnvLocal Environment = "local" EnvTest Environment = "test" EnvStaging Environment = "staging" EnvProduction Environment = "production" )
Standard list of valid execution environments.