Does calling the cancel func on a context that is attached to a 
http.Request change the contents of the body to context cancellation?

On Friday, 15 September 2017 18:15:25 UTC+1, Steven Lee wrote:
>
> Hello,
>
> I was wondering if anyone could help me with understanding the behaviour 
> of cancelling context on a request before its read.
>
> I am using golang 1.9 on macOS X sierra (latest)
>
> Sometimes this code returns context cancelled, sometimes it works.
>
> package main
>
> import (
>     "context"
>     "io/ioutil"
>     "log"
>     "net/http"
>     "time"
>
>     "golang.org/x/net/context/ctxhttp"
> )
>
> func main() {
>     req, err := http.NewRequest("GET", "https://swapi.co/api/people/1";, 
> nil)
>     if err != nil {
>         log.Fatal(err)
>     }
>     resp, err := fetch(req)
>     if err != nil {
>         log.Fatal(err)
>     }
>     log.Print(readBody(resp))
> }
>
> func fetch(req *http.Request) (*http.Response, error) {
>     ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second
> )
>     defer cancel()
>     return ctxhttp.Do(ctx, http.DefaultClient, req)
> }
>
> func readBody(resp *http.Response) (string, error) {
>     b, err := ioutil.ReadAll(resp.Body)
>     if err != nil {
>         return "", err
>     }
>     return string(b), err
> }
>
>
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to