Send a chunked HTTP response from a Go server

前端 未结 2 495
盖世英雄少女心
盖世英雄少女心 2020-12-14 02:32

I am creating a test Go HTTP server, and I am sending a response header of Transfer-Encoding: chunked so I can continually send new data as I retrieve it. This server should

相关标签:
2条回答
  • 2020-12-14 03:11

    It looks like httputil provides a NewChunkedReader function

    0 讨论(0)
  • 2020-12-14 03:24

    The trick appears to be that you simply need to call Flusher.Flush() after each chunk is written. Note also that the "Transfer-Encoding" header will be handled by the writer implicitly, so no need to set it.

    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))
    }
    

    You can verify by using telnet:

    $ 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
    
    ...
    

    You might need to do some research to verify that http.ResponseWriters support concurrent access for use by multiple goroutines.

    Also, see this question for more information about the "X-Content-Type-Options" header.

    0 讨论(0)
提交回复
热议问题