contextx

package
v0.0.24 Latest Latest
Warning

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

Go to latest
Published: Jan 18, 2025 License: MIT Imports: 4 Imported by: 3

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithValue

func WithValue(parent context.Context, k, v any) context.Context

WithValue like context.WithValue but faster

Example
package main

import (
	"context"
	"fmt"

	"github.com/xoctopus/x/contextx"
)

type key struct{}

func main() {
	ctx := contextx.WithValue(context.Background(), key{}, 100)

	fmt.Println(ctx.Value(key{}))
	fmt.Println(ctx.Value(1))
	fmt.Println(ctx)

}
Output:

100
<nil>
context.Background.WithValue(type contextx_test.key, val<not Stringer>)

Types

type Context added in v0.0.21

type Context[T any] interface {
	With(context.Context, T) context.Context
	From(context.Context) (T, bool)
	MustFrom(context.Context) T
	Compose(v T) WithContext
}

func New added in v0.0.21

func New[T any](options ...Option[T]) Context[T]

func NewValue added in v0.0.21

func NewValue[T any](v T) Context[T]

type Option added in v0.0.21

type Option[T any] func(*ctx[T])

func With added in v0.0.21

func With[T any](v T) Option[T]

func WithValuer added in v0.0.21

func WithValuer[T any](valuer Valuer[T]) Option[T]

type Valuer added in v0.0.21

type Valuer[T any] func() T

type WithContext

type WithContext = func(ctx context.Context) context.Context

func WithContextCompose

func WithContextCompose(withs ...WithContext) WithContext
Example
package main

import (
	"context"
	"fmt"
	"reflect"
	"time"

	"github.com/xoctopus/x/contextx"
)

type key struct{}

type fakeContext struct{}

func (fakeContext) Deadline() (time.Time, bool) { return time.Time{}, false }

func (fakeContext) Done() <-chan struct{} { return nil }

func (fakeContext) Err() error { return nil }

func (fakeContext) Value(any) any { return nil }

func main() {

	with := []contextx.WithContext{
		func(ctx context.Context) context.Context {
			return contextx.WithValue(ctx, key{}, 100)
		},
		func(ctx context.Context) context.Context {
			return contextx.WithValue(ctx, "key", "200")
		},
		func(ctx context.Context) context.Context {
			return contextx.WithValue(ctx, "key", reflect.ValueOf(1))
		},
	}

	compose := contextx.WithContextCompose(with...)

	ctx := compose(fakeContext{})
	fmt.Println(ctx.Value(key{}))
	fmt.Println(ctx)

	ctx = compose(context.Background())
	fmt.Println(ctx.Value(key{}))
	fmt.Println(ctx)

}
Output:

100
contextx_test.fakeContext.WithValue(type contextx_test.key, val<not Stringer>).WithValue(type string, val200).WithValue(type string, val<int Value>)
100
context.Background.WithValue(type contextx_test.key, val<not Stringer>).WithValue(type string, val200).WithValue(type string, val<int Value>)

Jump to

Keyboard shortcuts

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