contextx

package
v0.0.18 Latest Latest
Warning

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

Go to latest
Published: Jun 12, 2024 License: MIT Imports: 3 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 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