In the previous example we looked at setting up a simple
HTTP server. HTTP servers are useful for
demonstrating the usage of |
![]() ![]() package main |
import ( "fmt" "net/http" "time" ) |
|
func hello(w http.ResponseWriter, req *http.Request) { |
|
A |
ctx := req.Context() fmt.Println("server: hello handler started") defer fmt.Println("server: hello handler ended") |
Wait for a few seconds before sending a reply to the
client. This could simulate some work the server is
doing. While working, keep an eye on the context’s
|
select { case <-time.After(10 * time.Second): fmt.Fprintf(w, "hello\n") case <-ctx.Done(): |
The context’s |
err := ctx.Err() fmt.Println("server:", err) internalError := http.StatusInternalServerError http.Error(w, err.Error(), internalError) } } |
func main() { |
|
As before, we register our handler on the “/hello” route, and start serving. |
http.HandleFunc("/hello", hello) http.ListenAndServe(":8090", nil) } |
Run the server in the background. |
$ go run context-in-http-servers.go &
|
Simulate a client request to |
$ curl localhost:8090/hello server: hello handler started ^C server: context canceled server: hello handler ended |
Next example: Spawning Processes.