package main import ( "context" "fmt" ) func main() { ctx, cancel := context.WithCancel(context.Background()) go doSomething(ctx) // cancel the context after 1 second time.AfterFunc(time.Second, cancel) // handle canceled context error if err := ctx.Err(); err != nil { fmt.Println("Context error:", err) } } func doSomething(ctx context.Context) { // do some work select { case <-time.After(2 * time.Second): fmt.Println("Done!") case <-ctx.Done(): fmt.Println("Canceled:", ctx.Err()) } }
package main import ( "context" "fmt" "net/http" ) func main() { http.HandleFunc("/hello", helloHandler) http.ListenAndServe(":8080", nil) } func helloHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() // make a database call with a deadline of 1 second ctx, cancel := context.WithDeadline(ctx, time.Now().Add(1*time.Second)) defer cancel() // make database call with context result, err := db.QueryContext(ctx, "SELECT * FROM users") if err != nil { // check for context error if ctx.Err() != nil { w.WriteHeader(http.StatusRequestTimeout) fmt.Fprint(w, "Request timed out") return } w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, "Internal server error") return } // handle query result fmt.Fprint(w, result) }In this example, a context is created from the request's context using `r.Context()`. A database call is made with a deadline of 1 second using `context.WithDeadline()`. The `ctx.Err()` method is used to check for any context errors that occurred while making the database call. The http response status is set accordingly. The `context` package is a built-in package in Go.