Sobes.tech
Senior

What is context.WithValue used for?

sobes.tech AI

Answer from AI

context.WithValue is used to create a new context that contains a key-value pair. This allows passing additional data (such as request identifiers, authentication tokens) through a chain of calls without changing function signatures.

It is important to remember that the context is intended for passing data related to request processing, not for storing large structures or business logic.

Example of usage:

ctx := context.Background()
ctx = context.WithValue(ctx, "requestID", "12345")

func handleRequest(ctx context.Context) {
    if reqID, ok := ctx.Value("requestID").(string); ok {
        fmt.Println("Request ID:", reqID)
    }
}

handleRequest(ctx)