net/http/httptest

最後更新


net/http/httptest 讓你不必真的部署伺服器、也不必連外網,就能測試 HTTP Handler 與 HTTP 用戶端程式。

這個套件做什麼


測 HTTP 程式有兩種情境,這個套件各給一套工具:
情境工具是否開真的 port
測伺服器端 Handler:給它一個請求,看它回什麼NewRequest + NewRecorder否,直接呼叫函式
測用戶端程式:需要一個假的對方伺服器NewServer、NewTLSServer是,只聽 127.0.0.1 的隨機 port

ResponseRecorder 最快,適合大量的表格驅動測試;httptest.Server 走完整的網路流程(連線、標頭解析、TLS),適合測 http.Client 的設定或第三方 API 的包裝程式。
這些工具通常寫在 _test.go 裡(見單元測試)。為了讓範例可以直接 go run,本頁寫成 package main,用法在測試中完全相同。

匯入


  1. import "net/http/httptest"

常用 API


NewRequest 與 NewRecorder:直接測 Handler


NewRecorder 建立一個 *ResponseRecorder,它實作 http.ResponseWriter,會把 Handler 寫的狀態碼、標頭、內文記錄下來。NewRequest 建立一個「像是伺服器收到的」請求。把兩者交給 Handler 呼叫一次,再檢查 rec.Code、rec.Header()、rec.Body。
簽名:
  1. func NewRecorder() *ResponseRecorder
  2. func NewRequest(method, target string, body io.Reader) *http.Request

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/http/httptest"
  6. )
  7. func hello(w http.ResponseWriter, r *http.Request) {
  8. name := r.URL.Query().Get("name")
  9. if name == "" {
  10. http.Error(w, "name required", http.StatusBadRequest)
  11. return
  12. }
  13. w.Header().Set("Content-Type", "text/plain")
  14. fmt.Fprintf(w, "hello, %s", name)
  15. }
  16. func main() {
  17. for _, target := range []string{"/hello?name=Gopher", "/hello"} {
  18. req := httptest.NewRequest(http.MethodGet, target, nil)
  19. rec := httptest.NewRecorder()
  20. hello(rec, req)
  21. fmt.Printf("%d %q %q\n", rec.Code, rec.Header().Get("Content-Type"), rec.Body.String())
  22. }
  23. }

輸出:
  1. 200 "text/plain" "hello, Gopher"
  2. 400 "text/plain; charset=utf-8" "name required\n"

NewRequest 的預設值


target 可以只寫路徑,也可以寫完整網址。只寫路徑時,Host 預設為 example.com;RemoteAddr 固定是 192.0.2.1:1234(文件專用的保留位址);網址用 https 時會自動填上 r.TLS,讓 Handler 以為是 HTTPS 請求。傳入 strings.Reader 等內文時會自動設定 ContentLength。
需要帶 context 時改用 NewRequestWithContext(Go 1.23 起)。
簽名:
  1. func NewRequestWithContext(ctx context.Context, method, target string, body io.Reader) *http.Request

注意:NewRequest 遇到不合法的 method 或 target 會直接 panic,因為它是給測試用的,不回傳錯誤。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/http/httptest"
  6. "strings"
  7. )
  8. func main() {
  9. req := httptest.NewRequest("POST", "/upload?dry=1", strings.NewReader("abc"))
  10. fmt.Println(req.Method, req.URL.Path, req.URL.RawQuery)
  11. fmt.Println("Host:", req.Host)
  12. fmt.Println("RemoteAddr:", req.RemoteAddr)
  13. fmt.Println("ContentLength:", req.ContentLength)
  14. req2 := httptest.NewRequest("GET", "https://api.example.com/v1", nil)
  15. fmt.Println(req2.Host, req2.TLS != nil)
  16. var h http.Handler = http.NotFoundHandler()
  17. rec := httptest.NewRecorder()
  18. h.ServeHTTP(rec, req2)
  19. fmt.Println(rec.Code)
  20. }

輸出:
  1. POST /upload dry=1
  2. Host: example.com
  3. RemoteAddr: 192.0.2.1:1234
  4. ContentLength: 3
  5. api.example.com true
  6. 404

ResponseRecorder.Result:取得完整的 http.Response


rec.Code、rec.Body 適合簡單檢查。要檢查 cookie、或把結果交給「吃 *http.Response 的函式」,呼叫 Result() 取得一個 *http.Response,用法跟真的用戶端收到的回應一樣。
簽名:
  1. func (rw *ResponseRecorder) Result() *http.Response

注意:讀標頭請用 Result().Header 或 rec.Header();rec.HeaderMap 欄位已棄用。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. )
  8. func main() {
  9. h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  10. http.SetCookie(w, &http.Cookie{Name: "session", Value: "s-1"})
  11. w.WriteHeader(http.StatusAccepted)
  12. io.WriteString(w, "queued")
  13. })
  14. rec := httptest.NewRecorder()
  15. h.ServeHTTP(rec, httptest.NewRequest("POST", "/jobs", nil))
  16. resp := rec.Result()
  17. defer resp.Body.Close()
  18. body, _ := io.ReadAll(resp.Body)
  19. fmt.Println(resp.Status)
  20. fmt.Println(string(body))
  21. for _, c := range resp.Cookies() {
  22. fmt.Println("cookie:", c.Name, c.Value)
  23. }
  24. }

輸出:
  1. 202 Accepted
  2. queued
  3. cookie: session s-1

NewServer:起一個本機假伺服器


NewServer 立刻在 127.0.0.1 的隨機 port 啟動一個真正的 HTTP 伺服器,srv.URL 是它的網址(例如 http://127.0.0.1:54321,port 每次不同)。把這個網址交給你的用戶端程式,就能測試完整的請求流程而不連外網。srv.Client() 回傳一個已設定好、可連到這台伺服器的 *http.Client。
簽名:
  1. func NewServer(handler http.Handler) *Server
  2. func (s *Server) Client() *http.Client
  3. func (s *Server) Close()

注意:用完一定要 Close()(測試中寫 defer srv.Close()),它會等待所有進行中的請求結束。
範例:
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "net/http/httptest"
  7. "strings"
  8. )
  9. type weatherClient struct {
  10. baseURL string
  11. http *http.Client
  12. }
  13. func (c weatherClient) temp(city string) (float64, error) {
  14. resp, err := c.http.Get(c.baseURL + "/temp/" + city)
  15. if err != nil {
  16. return 0, err
  17. }
  18. defer resp.Body.Close()
  19. if resp.StatusCode != http.StatusOK {
  20. return 0, fmt.Errorf("status %d", resp.StatusCode)
  21. }
  22. var out struct {
  23. C float64 `json:"c"`
  24. }
  25. err = json.NewDecoder(resp.Body).Decode(&out)
  26. return out.C, err
  27. }
  28. func main() {
  29. mux := http.NewServeMux()
  30. mux.HandleFunc("GET /temp/{city}", func(w http.ResponseWriter, r *http.Request) {
  31. if r.PathValue("city") != "taipei" {
  32. http.NotFound(w, r)
  33. return
  34. }
  35. w.Header().Set("Content-Type", "application/json")
  36. w.Write([]byte(`{"c":28.5}`))
  37. })
  38. srv := httptest.NewServer(mux)
  39. defer srv.Close()
  40. fmt.Println("local URL:", strings.HasPrefix(srv.URL, "http://127.0.0.1:"))
  41. c := weatherClient{baseURL: srv.URL, http: srv.Client()}
  42. fmt.Println(c.temp("taipei"))
  43. fmt.Println(c.temp("mars"))
  44. }

輸出:
  1. local URL: true
  2. 28.5 <nil>
  3. 0 status 404

NewTLSServer:測 HTTPS


NewTLSServer 與 NewServer 相同,但走 HTTPS,憑證是套件內建的自簽憑證。一般的 http.DefaultClient 不信任這張憑證,所以要用 srv.Client(),它已經設定成信任該憑證。
簽名:
  1. func NewTLSServer(handler http.Handler) *Server

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "strings"
  8. )
  9. func main() {
  10. srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  11. fmt.Fprintf(w, "tls=%v proto=%s", r.TLS != nil, r.Proto)
  12. }))
  13. defer srv.Close()
  14. fmt.Println(strings.HasPrefix(srv.URL, "https://"))
  15. resp, err := srv.Client().Get(srv.URL)
  16. if err != nil {
  17. fmt.Println(err)
  18. return
  19. }
  20. body, _ := io.ReadAll(resp.Body)
  21. resp.Body.Close()
  22. fmt.Println(string(body))
  23. }

輸出:
  1. true
  2. tls=true proto=HTTP/1.1

NewUnstartedServer:先設定再啟動


想調整伺服器設定(例如開啟 HTTP/2、修改 http.Server 的欄位、關掉錯誤 log),用 NewUnstartedServer 建立但不啟動,改完 srv.Config(底層的 *http.Server)或 srv.EnableHTTP2 後,再呼叫 Start() 或 StartTLS()。
範例開啟 HTTP/2,並把錯誤 log 導到 io.Discard,所以預設用戶端因為不信任憑證而握手失敗時,伺服器不會印出 log。
簽名:
  1. func NewUnstartedServer(handler http.Handler) *Server
  2. func (s *Server) Start()
  3. func (s *Server) StartTLS()

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "log"
  6. "net/http"
  7. "net/http/httptest"
  8. )
  9. func main() {
  10. srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  11. fmt.Fprintf(w, "proto=%s", r.Proto)
  12. }))
  13. srv.EnableHTTP2 = true
  14. srv.Config.ErrorLog = log.New(io.Discard, "", 0)
  15. srv.StartTLS()
  16. defer srv.Close()
  17. resp, err := srv.Client().Get(srv.URL)
  18. if err != nil {
  19. fmt.Println(err)
  20. return
  21. }
  22. body, _ := io.ReadAll(resp.Body)
  23. resp.Body.Close()
  24. fmt.Println(resp.StatusCode, string(body))
  25. _, err = http.Get(srv.URL)
  26. fmt.Println("default client fails:", err != nil)
  27. }

輸出:
  1. 200 proto=HTTP/2.0
  2. default client fails: true

重點整理


  • 測 Handler:NewRequest + NewRecorder,直接呼叫,最快
  • 測用戶端:NewServer 起本機伺服器,把 srv.URL 交給被測程式,defer srv.Close()
  • HTTPS 用 NewTLSServer,並使用 srv.Client()
  • 要自訂設定用 NewUnstartedServer,改完再 Start/StartTLS
  • 檢查 cookie 或完整回應用 rec.Result();不要用已棄用的 HeaderMap

資料來源