gobyexample/httpctx/httpctx.go

31 lines
633 B
Go
Raw Permalink Normal View History

2024-05-04 18:32:38 +00:00
package httpctx
import (
"fmt"
"log"
"net/http"
"time"
)
func helloHandler(w http.ResponseWriter, req *http.Request) {
log.Println("hello handler started")
ctx := req.Context()
defer log.Println("hello handler finishing")
select {
case <-time.After(10 * time.Second):
fmt.Fprintln(w, "hello there!")
case <-ctx.Done():
err := ctx.Err()
log.Println("hello error:", err.Error())
internalError := http.StatusInternalServerError
http.Error(w, err.Error(), internalError)
}
}
func HttpCtx() {
log.Println("Server listening on :8002")
http.HandleFunc("/hello", helloHandler)
http.ListenAndServe(":8002", nil)
}