Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/qawatake/ctxvls
Package ctxvls provide APIs for storing and retrieving collections of values in context
https://github.com/qawatake/ctxvls
go golang
Last synced: 25 days ago
JSON representation
Package ctxvls provide APIs for storing and retrieving collections of values in context
- Host: GitHub
- URL: https://github.com/qawatake/ctxvls
- Owner: qawatake
- License: mit
- Created: 2023-10-14T11:30:33.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2023-10-16T13:22:30.000Z (about 1 year ago)
- Last Synced: 2024-10-29T12:57:10.557Z (2 months ago)
- Topics: go, golang
- Language: Go
- Homepage: https://pkg.go.dev/github.com/qawatake/ctxvls
- Size: 1.68 MB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# ctxvls
[![Go Reference](https://pkg.go.dev/badge/github.com/qawatake/ctxvls.svg)](https://pkg.go.dev/github.com/qawatake/ctxvls)
[![test](https://github.com/qawatake/ctxvls/actions/workflows/test.yaml/badge.svg)](https://github.com/qawatake/ctxvls/actions/workflows/test.yaml)Package `ctxvls` provide APIs for storing and retrieving collections of values in context, and it is designed to be safe for concurrent use.
```go
package mainimport (
"context"
"fmt""github.com/qawatake/ctxvls"
)func main() {
ctx := context.Background()
ctx = ctxvls.WithValues(ctx, "a", 1, 2, 3)
ctx = ctxvls.WithValues(ctx, "a", 2, 3, 4)
ctx = ctxvls.WithValues(ctx, "b", 3, 4, 5)
valuesForA := ctxvls.ValuesFrom[string, int](ctx, "a")
valuesForB := ctxvls.ValuesFrom[string, int](ctx, "b")
fmt.Println(valuesForA)
fmt.Println(valuesForB)
// Output:
// [1 2 3 2 3 4]
// [3 4 5]
}
```## Example usage
Wrapping the package allows for usage tailored to specific use cases.
```go
package mainimport (
"context""github.com/qawatake/ctxvls"
)type KV struct {
Key string
Value any
}func AddToContext(ctx context.Context, kvs ...KV) context.Context {
return ctxvls.WithValues(ctx, key{}, kvs...)
}func FromContext(ctx context.Context) []KV {
return ctxvls.ValuesFrom[key, KV](ctx, key{})
}type key struct{}
func main() {
ctx := context.Background()
ctx = AddToContext(ctx, KV{"a", 1}, KV{"b", 2})
ctx = AddToContext(ctx, KV{"b", 2}, KV{"c", 3})
kvs := FromContext(ctx)
fmt.Println(kvs)
// Output:
// [{a 1} {b 2} {b 2} {c 3}]
}
```