Junior — Middle
What is your experience with using contexts in your projects?
sobes.tech AI
Answer from AI
In my Go projects, I actively used the context package to manage operation timeouts and request cancellations. For example, when working with HTTP requests or databases, I created a context with a timeout to prevent hanging or resource leaks.
Example of using a context with a timeout:
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
result, err := db.QueryContext(ctx, "SELECT * FROM users")
if err != nil {
// handle error
}
I also used contexts to pass metadata between application layers, such as request identifiers for logging and tracing. This helps make the code more manageable and responsive to operation cancellations.