contextx

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2025 License: MIT Imports: 2 Imported by: 0

README

contextx

License Coverage GitHub Workflow Status Go Report Card Go PKG

Context value helper library.
Differences between context package this holds value in a map with mutex lock. Values readable from parent context.

go get github.com/rakunlabs/contextx

Usage

// set value first initialize context value map if not exist
ctx := contextx.WithValue(context.Background(), "secret", "xxx")

// map like access
if v, ok := contextx.Value[string](ctx, "secret"); ok {
    // v is string
}

Use WithKey option to set multiple data holder on same context.

Documentation

Overview

Example
package main

import (
	"context"
	"fmt"

	"github.com/rakunlabs/contextx"
)

func main() {
	ctx := contextx.WithValue(context.Background(), "secret", "xxx")

	if v, ok := contextx.Value[string](ctx, "secret"); ok {
		fmt.Println("[" + v + "]")
	}

	ctx = contextx.WithValue(ctx, "another", "yyy", contextx.WithKey("customKey"))

	if v, ok := contextx.Value[string](ctx, "another"); ok {
		fmt.Println("[" + v + "]")
	} else {
		// expected not found
		fmt.Println("not found")
	}

	if v, ok := contextx.Value[string](ctx, "secret", contextx.WithKey("customKey")); ok {
		fmt.Println("[" + v + "]")
	} else {
		// expected not found
		fmt.Println("not found")
	}

	if v, ok := contextx.Value[string](ctx, "another", contextx.WithKey("customKey")); ok {
		// expected found
		fmt.Println("[" + v + "]")
	}

}
Output:

[xxx]
not found
not found
[yyy]

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Init

func Init(ctx context.Context, opts ...Option) context.Context

Init context with internal value.

If context is nil, it use context.Background().

func Value

func Value[T any](ctx context.Context, key any, opts ...Option) (T, bool)

Value gets value from context's map.

Returns same as map's value and ok.

func WithValue

func WithValue(ctx context.Context, key, value any, opts ...Option) context.Context

WithValue sets value to context's map.

If context is nil, it use context.Background(). If context's map is nil, it will init context's map and add value to ctx.

Types

type CtxKey added in v0.2.0

type CtxKey string
const CtxInternal CtxKey = "internal"

type Data

type Data struct {
	V map[any]interface{}

	M sync.RWMutex
}

func Internal

func Internal(ctx context.Context, opts ...Option) (*Data, bool)

Internal gets internal data value from context.

If context is nil return nil and false.

type Option added in v0.2.0

type Option func(*option)

func WithKey added in v0.2.0

func WithKey(key any) Option

WithKey sets the key for the option.

Jump to

Keyboard shortcuts

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