In Go, the context package helps manage request-scoped values, cancellation signals, and deadlines.
Two common ways to start a context are context.TODO() and context.Background().
Though they behave similarly, they serve different purposes.
context.Background() is the default when you don’t need any special handling (like cancellation or deadlines).
It's often used in main, init, or when initializing operations that don't need a more specific context.
func main() { ctx := context.Background() server := http.Server{Addr: ":8080", BaseContext: func(net.Listener) context.Context { return ctx }} log.Fatal(server.ListenAndServe()) }
In this example, context.Background() is used to establish a base context for the HTTP server.
context.TODO() is a placeholder context. Use it when you're unsure of what context to provide or when planning to refactor later.
func processOrder() { ctx := context.TODO() // Placeholder, decision on context pending err := db.SaveOrder(ctx, orderData) if err != nil { log.Println("Failed to save order:", err) } }
Here, context.TODO() is temporarily used for a database operation until a more specific context is defined.
Both functions return an empty context, but they express different intentions:
When to Use context.Background():
When to Use context.TODO():
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3