Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func WithValue ¶
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 WithContext ¶
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>)
Click to show internal directories.
Click to hide internal directories.