How do I read a streaming response body using Golang's net/http package?

chourobin picture chourobin · Mar 1, 2014 · Viewed 21.5k times · Source

I am trying to connect to an endpoint that does http streaming of json data. I was wondering how to perform a basic request using Go's net/http package and read the response as it comes in. Currently, I am only able to read the response when the connection closes.

resp, err := http.Get("localhost:8080/stream")
if err != nil {
    ...
}
...
// perform work while connected and getting data

Any insight would be greatly appreciated!

Thanks!

-RC

Answer

chourobin picture chourobin · Mar 4, 2014

The answer provided by Eve Freeman is the correct way to read json data. For reading any type of data, you can use the method below:

resp, err := http.Get("http://localhost:3000/stream")
...

reader := bufio.NewReader(resp.Body)
for {
    line, err := reader.ReadBytes('\n')
    ...

    log.Println(string(line))
}