Intern
How to correctly pass context in a goroutine when sending an SMS (two-factor authentication)?
sobes.tech AI
Answer from AI
In Go, to pass context to a goroutine when sending an SMS (for example, for two-factor authentication), you should use the context package. The context allows you to control the lifetime of the operation, cancel it, and pass additional data.
The correct way:
- Create a context with a timeout or deadline to limit the SMS sending time.
- Pass this context to the goroutine and the sending function.
- Inside the sending function, check for context cancellation to abort the operation if necessary.
Example:
func sendSMS(ctx context.Context, phone, message string) error {
select {
case <-time.After(2 * time.Second):
// Simulate SMS sending
fmt.Println("SMS sent to", phone)
return nil
case <-ctx.Done():
return ctx.Err() // Cancellation or timeout
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
go func() {
err := sendSMS(ctx, "+1234567890", "Your code is 1234")
if err != nil {
fmt.Println("Failed to send SMS:", err)
}
}()
time.Sleep(5 * time.Second) // Wait for completion
}
This approach ensures control over execution time and allows proper handling of operation cancellation.