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
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.
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.
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.
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)) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With