Skip to content

Instantly share code, notes, and snippets.

@superbrothers
Created September 8, 2016 02:42
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save superbrothers/dae0030c151d1f3c24311df77405169b to your computer and use it in GitHub Desktop.
Save superbrothers/dae0030c151d1f3c24311df77405169b to your computer and use it in GitHub Desktop.
http request with context in Go
package main
import (
"context"
"fmt"
"log"
"net/http"
"time"
)
func main() {
req, err := http.NewRequest("GET", "http://www.yahoo.co.jp", nil)
if err != nil {
log.Fatalf("%v", err)
}
ctx, cancel := context.WithTimeout(req.Context(), 1*time.Millisecond)
defer cancel()
req = req.WithContext(ctx)
client := http.DefaultClient
res, err := client.Do(req)
if err != nil {
log.Fatalf("%v", err)
}
fmt.Printf("%v\n", res.StatusCode)
}
@prochac
Copy link

prochac commented Oct 7, 2019

@2minchul
Copy link

2minchul commented Dec 4, 2019

I made a simple example of NewRequestWithContext
https://gist.github.com/2minchul/6d344a0f1f85ead1530803df2e4f9894

@littlefuntik
Copy link

@itsgitz
Copy link

itsgitz commented Apr 2, 2021

There are many examples that use the parent context from context.Background(). But in this example, I see the parent is using r.Context() from request instead. So, which one that should I use?

@jpvillaseca
Copy link

There are many examples that use the parent context from context.Background(). But in this example, I see the parent is using r.Context() from request instead. So, which one that should I use?

it's actually the same. When he initialized the request with http.NewRequest(), per the documentation, the context of the request is the background context:

// NewRequest wraps NewRequestWithContext using the background context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment