For example if I had the code
t := time.Now()
http.Get("google.com")
fmt.Println(time.Now().Sub(t))
Would the printed duration be after the last byte of the response's body or after the last byte of the response's headers has been received?
For example if I had the code
t := time.Now()
http.Get("google.com")
fmt.Println(time.Now().Sub(t))
Would the printed duration be after the last byte of the response's body or after the last byte of the response's headers has been received?
The documentation doesn't clearly state that this, but it returns as soon as the response headers have been read.
As soon as you get a little experience with Go you'll realize that almost every time you get returned an io.Reader
(or in this case resp.Body
is an io.ReadCloser
) it's a streaming reader that doesn't have all the data yet.
Just like calling os.Open
returns something that can be used as an io.Reader
but doesn't read the whole file.
In many cases with Go, if the documentation is not clear,
you can look at the standard package code for enlightenment.
Admittedly, in this specific case (as with encoding/json
) the code is doing a lot so can be hard to follow at first glance.
Most of the standard packages are much easier to follow and learn from.
Failing that, you can just run a minor extension of the code you gave (on your own machine, the playground doesn't support making TCP connections) to make it pretty clear:
(note I just picked these URLs somewhat at random, better would be to pick some URL with a large payload that you know no one will mind you fetching for a test)
package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
)
func measure(url string) (t1, t2 time.Duration, n int64, err error) {
start := time.Now()
resp, err := http.Get(url)
if err != nil {
return
}
defer resp.Body.Close()
t1 = time.Since(start)
n, err = io.Copy(ioutil.Discard, resp.Body)
t2 = time.Since(start)
return
}
func main() {
for _, url := range []string{
"http://google.com/",
"http://en.wikipedia.org/",
"http://upload.wikimedia.org/wikipedia/commons/7/76/PIA02863_-_Jupiter_surface_motion_animation.gif",
} {
fmt.Printf("fetching %q ", url)
t1, t2, n, err := measure(url)
if err != nil {
fmt.Println("error:", err)
continue
}
fmt.Printf("got %d bytes in %v / %v
", n, t1, t2)
}
}
E.g. on a somewhat slow connection the final URL measured above says: 597.055907ms / 29.269763851s
.
(That is, the initial Get
call returned quickly whereas reading all the data took ~60 times longer.)