contextkit

package
v0.296.0 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2025 License: Apache-2.0 Imports: 5 Imported by: 2

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Detach

func Detach(parent context.Context) context.Context

func Merge added in v0.217.0

func Merge(ctxs ...context.Context) (context.Context, func())

Merge combines multiple contexts into one. The merged context will include all values from the source contexts. If any source context is cancelled, the merged context will be cancelled. If multiple source contexts have deadlines, the nearest deadline will be used for the merged context. The second function argument must be deferred to prevent goroutine leaks.

Example
package main

import (
	"context"
	"time"

	"go.llib.dev/frameless/pkg/contextkit"
)

func main() {
	type key string

	var (
		ctx1          = context.WithValue(context.Background(), key("foo"), 42)
		ctx2          = context.WithValue(context.Background(), key("bar"), 128)
		ctx3, cancel3 = context.WithTimeout(context.Background(), time.Hour)
	)
	defer cancel3()

	ctx, cancel := contextkit.Merge(ctx1, ctx2, ctx3)
	defer cancel()
	_ = ctx.Value(key("foo")) // 42
	_ = ctx.Value(key("bar")) // 128
	_, _ = ctx.Deadline()     // Deadline = deadline time value; OK=true
}

func WithoutCancel added in v0.244.0

func WithoutCancel(parent context.Context) context.Context

func WithoutValues added in v0.237.0

func WithoutValues(ctx context.Context) context.Context

Types

type ValueHandler added in v0.217.0

type ValueHandler[Key ~struct{}, Value any] struct{}
Example
package main

import (
	"context"

	"go.llib.dev/frameless/pkg/contextkit"
)

func main() {
	type MyContextKey struct{}
	type MyValueType string

	vic := contextkit.ValueHandler[MyContextKey, MyValueType]{}

	var ctx = context.Background() // empty context

	v, ok := vic.Lookup(ctx)
	_, _ = v, ok // "", false

	ctx = vic.ContextWith(ctx, "Hello, world!") // context with value

	v, ok = vic.Lookup(ctx)
	_, _ = v, ok // "Hello, world!", true
}

func (ValueHandler[Key, Value]) ContextWith added in v0.217.0

func (h ValueHandler[Key, Value]) ContextWith(ctx context.Context, v Value) context.Context

func (ValueHandler[Key, Value]) Lookup added in v0.217.0

func (h ValueHandler[Key, Value]) Lookup(ctx context.Context) (Value, bool)

Jump to

Keyboard shortcuts

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