ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com", nil) if err != nil { log.Fatal(err) } client := &http.Client{} resp, err := client.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close()
ctx := context.WithValue(context.Background(), "user_id", 1234) func getUserID(ctx context.Context) int { if userID, ok := ctx.Value("user_id").(int); ok { return userID } return 0 } userID := getUserID(ctx) fmt.Printf("User ID: %d", userID)In this example, we create a new context and store a user ID value in it. We then define a function that retrieves the value from the context. Finally, we call the function and print the value to the console. Overall the go context package provides convenient methods for handling request-scoped values, cancelation signals, and deadlines in Go applications.