Go's context package allows you to pass request-specific data using context.WithValue. However, it's not clear how to store multiple key-value pairs efficiently.
Consider the following options:
1. Multiple Calls to WithValue()
Call WithValue() multiple times, each time with a new key-value pair. This is straightforward but can be cumbersome.
2. Struct with Key-Value Pairs
Create a struct to hold all the key-value pairs and pass it as a single value to WithValue(). This allows easy access to all keys later, but can involve unnecessary copying of large data structures.
3. Hybrid Solution
Store key-value pairs in a map and create a wrapper struct that provides getters to access individual values. This allows safe concurrent access and avoids copying large amounts of data.
Here's an example of the hybrid solution:
type Values struct { m map[string]string } func (v Values) Get(key string) string { return v.m[key] } func main() { v := Values{map[string]string{ "1": "one", "2": "two", }} ctx := context.Background() ctx2 := context.WithValue(ctx, "myvalues", v) fmt.Println(ctx2.Value("myvalues").(Values).Get("2")) }
Output:
two
The best approach depends on the specific requirements. For performance-critical scenarios with many key-value pairs, the hybrid solution is recommended. Otherwise, multiple calls to WithValue() or a struct with key-value pairs may be more convenient.
The above is the detailed content of How to Pass Multiple Key-Value Pairs Efficiently with context.WithValue in Go?. For more information, please follow other related articles on the PHP Chinese website!