streaminghttptest

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 10, 2026 License: MIT Imports: 7 Imported by: 0

README

httptest-streaming

Go Reference

Test streaming http handlers in Go.

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

func Serve(t testing.TB, handler http.Handler, req *http.Request) *http.Response

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL