What are the known types of contexts in Go?
sobes.tech AI
Answer from AI
In Go, the standard context package provides several functions for creating contexts:
-
context.Background(): Returns a non-nil, empty context, which is typically used as the root context for incoming requests or main functions. It is never canceled, has no deadline, and carries no values. -
context.TODO(): Returns a non-nil, empty context. It is used when you are unsure about which context to use or when the code is not yet updated to accept a context. LikeBackground(), it is never canceled, has no deadline, and carries no values. It serves as a temporary placeholder. -
context.WithCancel(parent Context): Returns a derived context that can be canceled with the returnedcancelfunction. Canceling this context releases resources associated with it and its children.// Creating a cancellable context ctx, cancel := context.WithCancel(context.Background()) defer cancel() // Cancel the context upon function exit // Using ctx... -
context.WithDeadline(parent Context, deadline time.Time): Returns a derived context that will be automatically canceled at the specifieddeadline. It also returns acancelfunction that can be called earlier to cancel.// Creating a context with a deadline deadline := time.Now().Add(5 * time.Second) ctx, cancel := context.WithDeadline(context.Background(), deadline) defer cancel() // Using ctx... -
context.WithTimeout(parent Context, timeout time.Duration): Similar toWithDeadline, but takes a duration. It returns a derived context that will be automatically canceled after the specifiedtimeout.// Creating a context with a timeout ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() // Using ctx... -
context.WithValue(parent Context, key, val any): Returns a derived context that carries the specified key/value pair. It is used for passing request-specific data through the API.// Creating a context with a value type userIDKey string ctx := context.WithValue(context.Background(), userIDKey("user_id"), 123) // Retrieving the value from the context if userID, ok := ctx.Value(userIDKey("user_id")).(int); ok { // use userID }
These functions allow building a hierarchy of contexts, where child contexts inherit properties from parent contexts and can be canceled independently or when the parent is canceled.