Home >Backend Development >Golang >Why Doesn't My Go HTTP Server Send Chunked Responses Progressively?
HTTP Chunks Response from a Go Server
In this scenario, we aim to create a Go HTTP server that sends a chunked HTTP response with Transfer-Encoding set to "chunked." The server intends to write chunks at one-second intervals, allowing the client to receive them on demand. However, the current implementation faces challenges:
Server Code
The provided server code is as follows:
func HandlePost(w http.ResponseWriter, r *http.Request) { w.Header().Set("Connection", "Keep-Alive") w.Header().Set("Transfer-Encoding", "chunked") w.Header().Set("X-Content-Type-Options", "nosniff") ticker := time.NewTicker(time.Second) go func() { for t := range ticker.C { io.WriteString(w, "Chunk") fmt.Println("Tick at", t) } }() time.Sleep(time.Second * 5) ticker.Stop() fmt.Println("Finished: should return Content-Length: 0 here") w.Header().Set("Content-Length", "0") }
Solution
To resolve the issues:
Revised Code
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
Use telnet to connect to the server:
$ telnet localhost 8080 ... HTTP/1.1 200 OK Date: ... Content-Type: text/plain; charset=utf-8 Transfer-Encoding: chunked 9 Chunk #1 9 Chunk #2 ...
Each chunk will be received progressively as the server sends them.
The above is the detailed content of Why Doesn't My Go HTTP Server Send Chunked Responses Progressively?. For more information, please follow other related articles on the PHP Chinese website!