Testing HTTP handlers
The net/http/httptest
package also contains ResponseRecorder
, which can be used as http.ResponseWriter
for HTTP handlers to test a single handler without creating a server.
How to do it...
- Create
ResponseRecorder
:func TestHandler(t *testing.T) { w := httptest.NewRecorder()
- Call the handler, passing the response recorder instead of
http.ResponseWriter
:data, err := json.Marshal([]time.Time{ time.Date(2023, 2, 1, 12, 8, 37, 0, time.Local), time.Date(2021, 5, 6, 9, 48, 11, 0, time.Local), time.Date(2022, 11, 13, 17, 13, 54, 0, time.Local), time.Date(2022, 6, 23, 22, 29, 28, 0, time.Local), time.Date(2023, 3, 17, 4, 5, 9, 0, time.Local), }) if err != nil { t.Error(err) return } req, _ := http.NewRequest("POST", "localhost/sort/asc", bytes.NewReader(data)) req.Header.Set("Content-Type", "application/json") HandleSort(w...