Created
September 24, 2018 03:10
-
-
Save sponomarev/2b19a0393236f78978b15eaf3cf4331c to your computer and use it in GitHub Desktop.
Golang context to cancel HTTP request and response
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"io" | |
"log" | |
"net/http" | |
"time" | |
) | |
func main() { | |
// | |
ctx, cf := context.WithCancel(context.Background()) | |
// spawn a new HTTP server which emulates "long" work with 10 seconds timer | |
go func() { | |
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
ctx := r.Context() | |
fmt.Println("processing request") | |
select { | |
case <-time.After(10 * time.Second): | |
io.WriteString(w, "Hello, world!\n") | |
case <-ctx.Done(): | |
fmt.Println("processing cancelled") | |
} | |
}) | |
log.Fatal(http.ListenAndServe(":8080", nil)) | |
}() | |
// We use a simliest one approach to spawn a server without a way to be | |
// aknowledge | |
time.Sleep(1 * time.Second) | |
fmt.Println("we are all set") | |
// spawn a new worker with a request to fetch a page from the server | |
go func() { | |
client := http.DefaultClient | |
req, _ := http.NewRequest("GET", "http://localhost:8080", nil) | |
// Assign the context to the request | |
req = req.WithContext(ctx) | |
// Perform a request | |
res, err := client.Do(req) | |
fmt.Printf("%T:%+v\n", res, res) | |
fmt.Printf("%T:%+v\n", err, err) | |
}() | |
// Wait 3 seconds and cancel the request | |
time.Sleep(3 * time.Second) | |
fmt.Println("It's time to cancel request") | |
cf() | |
fmt.Scanln() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment