contextutil

package
v0.85.0-pre.2 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2026 License: BSD-3-Clause Imports: 3 Imported by: 0

README

kit/contextutil

github.com/vormadev/vorma/kit/contextutil

Typed wrappers for storing and reading values from context.Context.

Use this when you want to avoid repetitive type assertions and keep context keys isolated per concern.

Import

import "github.com/vormadev/vorma/kit/contextutil"

Basic Usage

type User struct {
	ID string
}

var userStore = contextutil.NewStore[User]("current-user")

ctx := userStore.ContextWithValue(context.Background(), User{ID: "u-1"})
user := userStore.Value(ctx)

Request Usage

req = userStore.RequestWithContextValue(req, User{ID: "u-1"})
user := userStore.Value(req.Context())

Important Semantics

  • Store identity is per Store[T] instance, not just key string text.
  • Missing or mismatched values return zero-value T.
  • Because zero-value can also be valid data, treat Value as a convenience API, not presence-proof.

Recommended pattern:

  • Define store variables once (usually package-level), and reuse them.
  • Avoid creating ad-hoc stores in many locations for the same logical value.

API Reference

  • type Store[T any]
  • func NewStore[T any](key string) *Store[T]
  • func (s *Store[T]) ContextWithValue(c context.Context, val T) context.Context
  • func (s *Store[T]) Value(c context.Context) T
  • func (s *Store[T]) RequestWithContextValue(r *http.Request, val T) *http.Request

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Store

type Store[T any] struct {
	// contains filtered or unexported fields
}

Store provides a typed key for context and request value access.

func NewStore

func NewStore[T any](key string) *Store[T]

NewStore creates a typed context store bound to a stable key name.

func (*Store[T]) ContextWithValue

func (s *Store[T]) ContextWithValue(c context.Context, val T) context.Context

ContextWithValue returns a derived context carrying val.

func (*Store[T]) RequestWithContextValue

func (s *Store[T]) RequestWithContextValue(
	r *http.Request,
	val T,
) *http.Request

RequestWithContextValue returns a request with val attached to its context.

func (*Store[T]) Value

func (s *Store[T]) Value(c context.Context) T

Value reads a typed value from context or returns the zero value.

Jump to

Keyboard shortcuts

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