package main import ( "context" "fmt" "time" "github.com/ryanmoran/stack" ) func main() { ctx := context.Background() ctx, cancel := context.WithTimeout(ctx, time.Second*5) defer cancel() go func() { err := doWork(ctx) if err != nil { fmt.Println("Request failed:", err) } }() select { case <-time.After(time.Second * 10): fmt.Println("Timed out after 10 seconds") case <-ctx.Done(): fmt.Println("Canceled request:", ctx.Err()) } } func doWork(ctx context.Context) error { // simulate long-running operation time.Sleep(time.Second * 7) // check context for cancellation select { case <-ctx.Done(): return fmt.Errorf("Request canceled: %v", ctx.Err()) default: } return nil }
package main import ( "context" "fmt" "github.com/ryanmoran/stack" ) func main() { ctx := context.Background() ctx = stack.New(ctx) // add a value to the stack ctx = stack.WithValue(ctx, "key", "value1") // retrieve the value from the stack v1, ok := stack.Value(ctx, "key").(string) if !ok { fmt.Println("Value not found") } fmt.Println(v1) // add another value to the stack ctx = stack.WithValue(ctx, "key", "value2") // retrieve the new value from the stack v2, ok := stack.Value(ctx, "key").(string) if !ok { fmt.Println("Value not found") } fmt.Println(v2) // retrieve the original value from the stack v3, ok := stack.ParentValue(ctx, "key").(string) if !ok { fmt.Println("Value not found") } fmt.Println(v3) }Example #2 demonstrates how to use Context to manage request-scoped data using a stack model. In this example, a new context is created using `stack.New` and a value is added to the stack using `stack.WithValue`. The value is retrieved using `stack.Value` and then a new value is added using `stack.WithValue`. The original value is retrieved again using `stack.ParentValue` and printed to the console. This allows for multiple values to exist on the stack, each with their own scope, and then access them in the correct order. The package library therefore is a Golang library named "stack".