package main import ( "context" "fmt" "time" ) func main() { ctx := context.Background() ctx, cancel := context.WithDeadline(ctx, time.Now().Add(5*time.Second)) defer cancel() select { case <- time.After(10*time.Second): fmt.Println("Finished") case <- ctx.Done(): fmt.Println(ctx.Err().Error()) } }
package main import ( "context" "fmt" ) type key int const nameKey key = 0 func main() { ctx := context.WithValue(context.Background(), nameKey, "Alice") hello(ctx) } func hello(ctx context.Context) { name := ctx.Value(nameKey).(string) fmt.Println("Hello,", name) }This example uses `WithValue()` to create a context with request-scoped data. It creates a `key` constant to uniquely identify the value and sets it to `0`. Then it creates a context with the `WithValue()` function, setting the value of `nameKey` to `"Alice"`. Finally, it calls the `hello()` function passing the context and uses the `Value()` method to retrieve the value associated with `nameKey`. The output is `"Hello, Alice"`. In conclusion, the `Context` package belongs to the `net` package library and is used to manage the state and errors associated with a request's lifecycle in a concurrent environment. The package provides powerful features like cancellation, deadline management, timeout, and request-scoped data sharing.