Home >Backend Development >Golang >Why Doesn't My Go HTTP Server Send Chunked Responses Progressively?

Why Doesn't My Go HTTP Server Send Chunked Responses Progressively?

DDD
DDDOriginal
2024-12-09 09:21:09164browse

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:

  1. The client is receiving all chunks at once instead of progressively as intended.
  2. The Content-Length header is automatically set by Go, which we want to be 0 and added at the end.

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:

  1. The "Flusher" interface implemented by http.ResponseWriter allows us to trigger chunk sending by calling the Flush() function. By adding this after each chunk is written, the client can receive chunks as they are ready.
  2. The Transfer-Encoding header is automatically managed by the HTTP writer, so setting it explicitly is unnecessary.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn