Home >Backend Development >Golang >How to Send Chunked HTTP Responses from a Go Server?
Send a Chunked HTTP Response from a Go Server
Solution:
To send chunked HTTP responses from a Go server and receive them in real time, it's necessary to invoke Flusher.Flush() after writing each data chunk. This triggers the "chunked" encoding and immediately sends the chunk to the client. Here's an example of how to implement this:
package main import ( "fmt" "io" "log" "net/http" "time" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { flusher, ok := w.(http.Flusher) if !ok { panic("expected http.ResponseWriter to be an http.Flusher") } w.Header().Set("X-Content-Type-Options", "nosniff") for i := 1; i <= 10; i++ { fmt.Fprintf(w, "Chunk #%d\n", i) flusher.Flush() // Trigger "chunked" encoding and send a chunk... time.Sleep(500 * time.Millisecond) } }) log.Print("Listening on localhost:8080") log.Fatal(http.ListenAndServe(":8080", nil)) }
Verification:
Using telnet, you can connect to the server and witness the chunked response being delivered:
$ telnet localhost 8080 Trying ::1... Connected to localhost. Escape character is '^]'. GET / HTTP/1.1 HTTP/1.1 200 OK Date: Tue, 02 Jun 2015 18:16:38 GMT Content-Type: text/plain; charset=utf-8 Transfer-Encoding: chunked 9 Chunk #1 9 Chunk #2 ...
Additional Notes:
The above is the detailed content of How to Send Chunked HTTP Responses from a Go Server?. For more information, please follow other related articles on the PHP Chinese website!