Middle+
Is it possible to put a structure into the context via context.WithValue?
sobes.tech AI
Answer from AI
Yes, in Go you can store a struct in the context using context.WithValue. However, it is important to remember that the context is intended for passing request-related data such as timeouts, deadlines, and metadata, not for passing large or mutable structures.
Example:
Type User struct {
ID int
Name string
}
ctx := context.Background()
user := &User{ID: 1, Name: "Alice"}
ctx = context.WithValue(ctx, "user", user)
// Retrieval
u, ok := ctx.Value("user").(*User)
if ok {
fmt.Println(u.Name)
}
It is recommended to use key types that do not conflict with other packages, such as custom key types, to avoid collisions.