Sobes.tech
Senior

What is context in Go and why is it needed?

sobes.tech AI

Answer from AI

In Go, context is a package and a type used to pass information about deadlines, cancellation signals, and other request-scoped values across API boundaries and goroutines.

Main purposes of context:

  • Cancel operations: Allows canceling a goroutine or a chain of calls, for example, on timeout or request cancellation.
  • Pass deadlines: You can set a time after which the operation should be aborted.
  • Pass values: Context can carry key-value pairs for passing data between functions (e.g., request ID).

Example usage:

func fetchData(ctx context.Context) error {
    req, _ := http.NewRequest("GET", "http://example.com", nil)
    req = req.WithContext(ctx) // associate request with context

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return err
    }
    defer resp.Body.Close()
    // process response
    return nil
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()

    err := fetchData(ctx)
    if err != nil {
        fmt.Println("Error or cancellation:", err)
    }
}

Thus, context helps manage the lifetime of operations and coordinate their cancellation, which is especially important in networked and concurrent applications.