Documentation
¶
Overview ¶
Example ¶
package main
import (
"context"
"fmt"
"github.com/xoctopus/x/contextx"
)
type tCtxT struct{}
func main() {
ctx := contextx.Carry[tCtxT]("100")(context.Background())
fmt.Println(contextx.Must[tCtxT, string](ctx))
}
Output: 100
Index ¶
- func From[K comparable, T any](ctx context.Context) (T, bool)
- func Must[K comparable, T any](ctx context.Context) T
- func With[K comparable, T any](ctx context.Context, v T) context.Context
- func WithValue(parent context.Context, k, v any) context.Context
- type Carrier
- type Context
- type Option
- type Valuer
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func WithValue ¶
WithValue like context.WithValue but faster🤏
Example ¶
var ctx context.Context
type key1 struct{}
type key2 struct{}
type key3 struct{}
type key4 struct{}
ctx = contextx.WithValue(MockContext{}, key1{}, "1")
fmt.Println(ctx)
ctx = contextx.WithValue(ctx, key2{}, "2")
fmt.Println(ctx)
ctx = contextx.WithValue(ctx, key3{}, net.IPv4(1, 1, 1, 1))
fmt.Println(ctx)
ctx = contextx.WithValue(ctx, key4{}, 4)
fmt.Println(ctx)
fmt.Println("context value key1:", ctx.Value(key1{}))
fmt.Println("context value key2:", ctx.Value(key2{}))
fmt.Println("context value key3:", ctx.Value(key3{}))
fmt.Println("context value key4:", ctx.Value(key4{}))
Output: contextx_test.MockContext.WithValue(key:contextx_test.key1, val:1) contextx_test.MockContext.WithValue(key:contextx_test.key1, val:1).WithValue(key:contextx_test.key2, val:2) contextx_test.MockContext.WithValue(key:contextx_test.key1, val:1).WithValue(key:contextx_test.key2, val:2).WithValue(key:contextx_test.key3, val:1.1.1.1) contextx_test.MockContext.WithValue(key:contextx_test.key1, val:1).WithValue(key:contextx_test.key2, val:2).WithValue(key:contextx_test.key3, val:1.1.1.1).WithValue(key:contextx_test.key4, val:<not Stringer>) context value key1: 1 context value key2: 2 context value key3: 1.1.1.1 context value key4: 4
Types ¶
type Carrier ¶ added in v0.2.1
func Carry ¶ added in v0.3.0
func Carry[K comparable, T any](v T) Carrier
func Compose ¶ added in v0.0.25
Example ¶
c1 := contextx.NewT[string]()
c2 := contextx.NewT[int]()
c3 := contextx.NewT[fmt.Stringer]()
ctx := contextx.Compose(
c1.Carry("1"),
c2.Carry(2),
c3.Carry(net.IPv4(1, 1, 1, 1)),
)(context.Background())
fmt.Println(ctx)
fmt.Println(c1.MustFrom(ctx))
fmt.Println(c2.MustFrom(ctx))
fmt.Println(c3.MustFrom(ctx))
Output: context.Background.WithValue(key:*contextx.ctx[string], val:1).WithValue(key:*contextx.ctx[int], val:<not Stringer>).WithValue(key:*contextx.ctx[fmt.Stringer], val:1.1.1.1) 1 2 1.1.1.1
type Context ¶ added in v0.0.21
Click to show internal directories.
Click to hide internal directories.