Junior — Middle
What is the purpose of using context in your project or code?
sobes.tech AI
Answer from AI
In Go, the context (context.Context) is used to pass information about execution state, such as timeouts, deadlines, cancellation signals, and to transfer values between goroutines.
Purpose of using context:
- Managing the lifetime of requests and operations (e.g., cancel an HTTP request when the client disconnects).
- Passing metadata (e.g., request IDs for logging).
- Ensuring cancellation of a chain of calls if needed.
Example:
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
// Pass ctx to functions that can be canceled
result, err := doSomething(ctx)
if err == context.DeadlineExceeded {
fmt.Println("Operation canceled due to timeout")
}
Thus, context helps control execution and share data between application components.