Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 962
chourobin Avatar asked Mar 01 '14 00:03

chourobin


People also ask

What is streaming HTTP response?

HTTP Streaming is a push-style data transfer technique that allows a web server to continuously send data to a client over a single HTTP connection that remains open indefinitely.

What is HTTP ListenAndServe?

NewServeMux() mux. HandleFunc("/", indexHandler) log. Fatal(http. ListenAndServe(":8080", mux)) } An HTTP ServeMux is essentially a request router that compares incoming requests against a list of predefined URL paths and executes the associated handler for the path whenever a match is found.

What is net HTTP in Golang?

The net/http interface encapsulates the request-response pattern in one method: type Handler interface { ServeHTTP(ResponseWriter, *Request) } Implementors of this interface are expected to inspect and process data coming from the http. Request object and write out a response to the http. ResponseWriter object.


1 Answers

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)) } 
like image 165
chourobin Avatar answered Sep 21 '22 17:09

chourobin