Response Controller Deadlines And Flush

Drive per-response write deadlines and explicit flushes through ResponseController so streamed output reaches clients before the handler returns.

GoData Fetching

Code

gosnippet
45 lines
package main

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

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/stream", func(w http.ResponseWriter, r *http.Request) {
		// ResponseController 统一访问底层连接的 Flush 与 Deadline 能力
		rc := http.NewResponseController(w)
		if err := rc.SetWriteDeadline(time.Now().Add(2 * time.Second)); err != nil {
			fmt.Println("deadline unsupported:", err)
		}
		for i := 1; i <= 3; i++ {
			fmt.Fprintf(w, "chunk-%d\n", i)
			if err := rc.Flush(); err != nil {
				fmt.Println("flush failed:", err)
				return
			}
		}
	})
	server := httptest.NewServer(mux)
	defer server.Close()

	resp, err := http.Get(server.URL + "/stream")
	if err != nil {
		fmt.Println("request failed:", err)
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("read failed:", err)
		return
	}
	fmt.Println("body bytes:", len(body))
	fmt.Println("body:", string(body))
	fmt.Println("status:", resp.StatusCode)
}

Inside the snippet

Response Controller Deadlines And Flush keeps everything in the function main.

for i := 1; i <= 3; i++ is the loop that carries the per-item work. Nothing falls through silently — 4 checkpoints test err != nil on the way through. The cleanup call is deferred to function exit — success, early return, and panic all covered.

Using it

The demo output is labeled (deadline unsupported:, flush failed:, request failed:), so the printed output reads as a trace of the operations performed.

Key statements

if err != nil {
	fmt.Println("request failed:", err)
	return
}
if err != nil {
	fmt.Println("read failed:", err)
	return
}
defer resp.Body.Close()

Interactive Tools for This Topic

FAQ

What does Response Controller Deadlines And Flush print when run?
The script runs standalone; its 7 labeled outputs include `deadline unsupported:`, `flush failed:`, `request failed:`.