Documentation
¶
Overview ¶
Package streaminghttptest supports testing for streaming http handlers.
This package is intended to complement net/http/httptest. Serve wraps and enhances net/http/httptest.ResponseRecorder, allowing full-multiplex streaming between a handler and response consumer in tests without a net/http/httptest.Server.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Serve ¶
Serve invokes an http handler with the given req and returns the response generated by the handler.
Serve returns following the first flush of response data. The handler runs in a separate goroutine and may continue running after Serve returns. Additional writes to http.ResponseWriter within the handler may be read by the response consumer.
This allows full-multiplex streaming between the handler and the response consumer in tests.
If req is created by httptest.NewRequestWithContext(t.Context(), ...) then Serve will drain the response body during test cleanup to avoid resource/goroutine leaks.
Example ¶
t := &testing.T{} // provided by test
handler := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
rc := http.NewResponseController(rw)
_, _ = rw.Write([]byte("server says hello"))
_ = rc.Flush() // streaminghttptest.Serve returns after first flush
buf := make([]byte, 1024)
n, _ := r.Body.Read(buf)
fmt.Println(string(buf[:n]))
})
rd, reqBody := io.Pipe()
req := httptest.NewRequestWithContext(context.Background() /* t.Context() */, "GET", "/", rd)
resp := streaminghttptest.Serve(t, handler, req)
buf := make([]byte, 1024)
n, _ := resp.Body.Read(buf)
fmt.Println(string(buf[:n]))
_, _ = reqBody.Write([]byte("client says hello"))
Output: server says hello client says hello
Types ¶
This section is empty.