Adding example of HTTP server using context.Context
This commit is contained in:
parent
43825687bb
commit
ff70f04795
42
examples/context-in-http-servers/context-in-http-servers.go
Normal file
42
examples/context-in-http-servers/context-in-http-servers.go
Normal file
@ -0,0 +1,42 @@
|
||||
// In the previous example we looked at setting up a simple
|
||||
// [HTTP server](http-servers). HTTP servers are useful for
|
||||
// demonstrating the usage of `context.Context` for
|
||||
// controlling cancellation.
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
func hello(w http.ResponseWriter, req *http.Request) {
|
||||
// A `context.Context` is created for each request by
|
||||
// the `net/http` machinery, and is available with
|
||||
// the `Context()` method.
|
||||
ctx := req.Context()
|
||||
fmt.Println("server: hello handler started")
|
||||
defer fmt.Println("server: hello handler ended")
|
||||
|
||||
// Wait for 3 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
|
||||
// `Done()` channel for a signal that we should cancel
|
||||
// the work and return as soon as possible.
|
||||
select {
|
||||
case <-time.After(3 * time.Second):
|
||||
fmt.Fprintf(w, "hello\n")
|
||||
case <-ctx.Done():
|
||||
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)
|
||||
}
|
@ -0,0 +1,2 @@
|
||||
4ec814bf1b01bf71fb95007cad39586ad87e3fb6
|
||||
k3vHfk-r3EE
|
11
examples/context-in-http-servers/context-in-http-servers.sh
Normal file
11
examples/context-in-http-servers/context-in-http-servers.sh
Normal file
@ -0,0 +1,11 @@
|
||||
# Run the server in the background.
|
||||
$ go run context-in-http-servers.go &
|
||||
|
||||
# Simulate a client request to `/hello`, hitting
|
||||
# Ctrl+C shortly after starting to signal
|
||||
# cancellation.
|
||||
$ curl localhost:8090/hello
|
||||
server: hello handler started
|
||||
^C
|
||||
server: context canceled
|
||||
server: hello handler ended
|
Loading…
x
Reference in New Issue
Block a user