Home >Backend Development >Golang >Why Does My Go HTTP Server Only Send Chunked Data After a Delay, and How Can I Set Content-Length to 0?

Why Does My Go HTTP Server Only Send Chunked Data After a Delay, and How Can I Set Content-Length to 0?

Barbara Streisand
Barbara StreisandOriginal
2024-12-04 08:12:13432browse

Why Does My Go HTTP Server Only Send Chunked Data After a Delay, and How Can I Set Content-Length to 0?

Continuous Chunked HTTP Response from Go Server

In an effort to create a Go HTTP server that continuously transmits chunks of data, you've encountered a challenge. Instead of receiving chunks as intended every second, your client only receives the entire response after a 5-second duration. Additionally, you're seeking to send the Content-Length header as 0 at the end of the transmission.

To resolve this issue, it's essential to integrate the Flusher interface into your server implementation. Here's an amended version of your code:

package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
    "time"
)

func main() {
    http.HandleFunc("/test", HandlePost)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func HandlePost(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")

    ticker := time.NewTicker(time.Second)
    go func() {
        for t := range ticker.C {
            io.WriteString(w, "Chunk")
            fmt.Println("Tick at", t)
            flusher.Flush()
        }
    }()
    time.Sleep(time.Second * 5)
    ticker.Stop()
    fmt.Println("Finished: should return Content-Length: 0 here")
    w.Header().Set("Content-Length", "0")
}

By invoking Flusher.Flush() after each chunk is written, you trigger the "chunked" encoding and send individual chunks. This ensures that the client receives data as it becomes available.

Verifying this behavior can be achieved through telnet, as demonstrated below:

$ 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

...

This modified code enables sending a Continuous Chunked HTTP response from your Go server. Remember to verify that your ResponseWriters support concurrent access across multiple goroutines for optimal performance.

The above is the detailed content of Why Does My Go HTTP Server Only Send Chunked Data After a Delay, and How Can I Set Content-Length to 0?. 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