33 lines604 B

package main
import (
"context"
"fmt"
"net/http"
"time"
)
func slowReport(ctx context.Context) (string, error) {
select {
case <-time.After(3 * time.Second):
return "report ready", nil
case <-ctx.Done():
return "", ctx.Err()
}
}
func handler(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), time.Second)
defer cancel()
msg, err := slowReport(ctx)
if err != nil {
http.Error(w, err.Error(), http.StatusGatewayTimeout)
return
}
fmt.Fprintln(w, msg)
}
func main() {
http.HandleFunc("/report", handler)
http.ListenAndServe(":8080", nil)
}