Home > Backend Development > Golang > How to Send Chunked HTTP Responses from a Go Server?

How to Send Chunked HTTP Responses from a Go Server?

Barbara Streisand
Release: 2024-12-01 19:50:11
Original
694 people have browsed it

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))
}
Copy after login

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

...
Copy after login

Additional Notes:

  • It's worth researching whether http.ResponseWriters support concurrent access for simultaneous use by multiple goroutines.
  • For more information on the "X-Content-Type-Options" header, consult this related question.

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!

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template