httptest Recorder Tests A Handler
Drive an http.HandlerFunc with httptest.NewRequest and a response recorder so handler logic, headers, and error paths run without opening a listener.
Code
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
)
// greetHandler 是业务代码,不知道自己在被测试
func greetHandler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if name == "" {
http.Error(w, "name is required", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"greeting": "hello " + name})
}
func main() {
// Recorder 收集响应:不开监听端口就能完整执行 handler
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/greet?name=ada", nil)
greetHandler(rec, req)
fmt.Println("status:", rec.Code)
fmt.Println("content-type:", rec.Header().Get("Content-Type"))
fmt.Println("body:", rec.Body.String())
// 缺参路径:状态码与错误体同样可断言
bad := httptest.NewRecorder()
greetHandler(bad, httptest.NewRequest(http.MethodGet, "/greet", nil))
fmt.Println("missing name:", bad.Code, bad.Body.String())
}What the code does
The operative core is the functions greetHandler and main — everything else is wiring.
Watch out for
- Nothing needs declaring — the runtime ships every API this handler test uses.
Applying it
Entry point, spelled out: func greetHandler(w http.ResponseWriter, r *http.Request)
The run emits 4 labeled sections — status:, content-type:, body:, missing name: — one per step.
Execute the file and main walks through greetHandler, in that order.
Statements that carry the logic
func greetHandler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if name == "" {
http.Error(w, "name is required", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"greeting": "hello " + name})
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.
FAQ
- What does httptest Recorder Tests A Handler print when run?
- Execute the whole file; each printed line is prefixed with a label like `status:`, `content-type:`, `body:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.