Sobes.tech
Middle+

What is the purpose of passing metadata through context?

sobes.tech AI

Answer from AI

In Go, the context (context.Context) is used to pass metadata such as deadlines, cancellation signals, and additional values between functions and goroutines.

Passing metadata through the context allows:

  • Managing the lifetime of a request (e.g., canceling operations on timeout).
  • Transmitting information without changing function signatures (e.g., user ID, tokens).
  • Ensuring thread safety and convenience in passing data along call chains.

Example of passing a value through context:

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

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

process(ctx)
What is the purpose of passing metadata through… - sobes.tech