Sobes.tech
Junior — Middle

Mis on konteksti kasutamise eesmärk teie projektis või koodis?

sobes.tech AI

Vastus AI-lt

In Go, the context.Context is used to pass information about the execution state, such as timeouts, deadlines, and cancellation signals, as well as to transfer values between goroutines.

Purpose of using context:

  • Managing the lifecycle of requests and operations (e.g., cancel an HTTP request when the client closes).
  • Transmitting metadata (e.g., request identifiers for logging).
  • Ensuring the cancellation of call chains when necessary.

Example of usage:

ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()

// Pass ctx to a function that can be interrupted by a timeout
result, err := doSomething(ctx)
if err == context.DeadlineExceeded {
    fmt.Println("Operation was canceled due to timeout")
}

This way, the context helps control execution and exchange data between application components.