LoginSignup
3
2

More than 5 years have passed since last update.

httptestでエラーを返したい時

Last updated at Posted at 2015-01-17

テスト用のモックサーバーを作るために
httptest.NewServer()作ったときのエラーの作り方。

  ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusBadRequest)
    fmt.Fprint(w, "Bad Request")
  }))
  defer ts.Close()

Headerへの書き込みより先に、Bodyの書き込みをしてはいけない。

ダメ
  ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Bad Request")
    w.WriteHeader(http.StatusBadRequest)
}
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2