contextx

package
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2025 License: Apache-2.0 Imports: 1 Imported by: 6

Documentation

Overview

Package contextx is a helper package for managing context values Most **request-scoped data** is a singleton per request That is, it doesn't make sense for a request to carry around multiple loggers, users, traces you want to carry the _same one_ with you from function call to function call the way we've handled this historically is a separate context key per type you want to carry in the struct but with generics, instead of having to make a new zero-sized type for every struct we can just make a single generic type and use it for everything which is what this helper package is intended to do

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func From

func From[T any](ctx context.Context) (T, bool)

From returns the value associated with the wanted type from the context It performs a type assertion to convert the value to the desired type T If the type assertion is successful, it returns the value and true If the type assertion fails, it returns the zero value of type T and false

func FromOr

func FromOr[T any](ctx context.Context, def T) T

FromOr returns the value associated with the wanted type or the given default value if the type is not found This function is useful when you want to ensure that a value is always returned from the context, even if the context does not contain a value of the desired type. By providing a default value, you can avoid handling the case where the value is missing and ensure that your code has a fallback value to use

func FromOrFunc

func FromOrFunc[T any](ctx context.Context, f func() T) T

FromOrFunc returns the value associated with the wanted type or the result of the given function if the type is not found This function is useful when the default value is expensive to compute or when the default value depends on some runtime conditions

func MustFrom

func MustFrom[T any](ctx context.Context) T

MustFrom is similar to from, except that it panics if the type assertion fails / the value is not in the context

func With

func With[T any](ctx context.Context, v T) context.Context

With returns a copy of parent that contains the given value which can be retrieved by calling From with the resulting context The function uses a generic key type to ensure that the stored value is type-safe and can be uniquely identified and retrieved without risk of key collisions

Types

This section is empty.

Jump to

Keyboard shortcuts

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