Junior — Middle
Kuidas rakendada oma Go rakenduses konteksti ajapiirangut?
sobes.tech AI
Vastus AI-lt
In Go, to implement a context timeout, the context package is used. A context with a timeout is created using the context.WithTimeout function, which returns a new context and a cancellation function.
Example:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
select {
case <-time.After(3 * time.Second):
fmt.Println("operation completed")
case <-ctx.Done():
fmt.Println("timeout or context cancellation:", ctx.Err())
}
In this example, if the operation takes longer than 2 seconds, the context is canceled and the timeout can be handled. This is useful for limiting the execution time of functions, requests, etc.