Junior — Middle
How can you manage the timeout for confirmation code acceptance during authentication?
sobes.tech AI
Answer from AI
In Go, managing the timeout for waiting for an authentication code confirmation is usually implemented using context (context.Context) or timers (time.Timer, time.After). For example, you can create a context with a timeout that cancels the operation if the confirmation does not arrive in time:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Start waiting for confirmation in a separate goroutine
select {
case <-confirmationChan:
// Code confirmed
case <-ctx.Done():
// Timeout expired, handle error
}
You can also use time.After for a simple timeout:
select {
case <-confirmationChan:
// Code confirmed
case <-time.After(30 * time.Second):
// Timeout
}
Thus, timeouts allow controlling the maximum waiting time for the code confirmation and properly handling situations where the user does not enter the code in time.