context

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2025 License: MIT-0 Imports: 1 Imported by: 0

Documentation

Overview

Package context provides utils for universal context.Context typed manipulations by generics.

Example
package main

import (
	"context"
	"fmt"

	contextutil "source.toby3d.me/toby3d/hacks/context"
)

func main() {
	type Username string

	var user Username = "toby3d"

	f := func(ctx context.Context) {
		// Retrieve typed value from parent context if exist.
		if name, exist := contextutil.Value[Username](ctx); exist {
			fmt.Printf("Hi, %s!\n", name)
		} else {
			fmt.Println("Access denied")
		}
	}

	ctx := context.Background()
	f(ctx)

	// Store some metadata in context.
	ctx = contextutil.WithValue(ctx, user)
	f(ctx)

}
Output:

Access denied
Hi, toby3d!

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Value

func Value[T any](ctx context.Context) (T, bool)

Value return value under provided T context key and cast it into T for return. Return false if context key does not exists or cannot be casted into T.

func WithValue

func WithValue[T any](parent context.Context, v T) context.Context

WithValue store value under it's type in context.Context.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳