Go1.11からnet/http/httptestのResponseRecorder.HeaderMapがdepricatedになってるので、Response.Headerを使っていきましょう。
net/http/httptest ResponseRecorder.HeaderMap
httpリクエストのハンドラーのテストなどで、レスポンスのHeaderの値を取得する際などに使っていたものです。
// HeaderMap contains the headers explicitly set by the Handler.
// It is an internal detail.
//
// Deprecated: HeaderMap exists for historical compatibility
// and should not be used. To access the headers returned by a handler,
// use the Response.Header map as returned by the Result method.
HeaderMap http.Header
こちらは、下記のPRを持ってdepricateとなったようです。
書き換え方
これまで、HeaderMap
を使った場合は次のようにテストコードが書けます。
handler_test.go
func TestHandler(t *testing.T) {
// httptestの準備
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/tests", nil)
TestHandler(w, r)
// 各種チェック
res := w.Result()
defer res.Body.Close()
// Content-Typeのチェック
if expected := "application/json; charset=utf-8"; w.HeaderMap.Get("Content-Type") != expected {
t.Errorf("unexpected response Content-Type, expected: %#v, but given #%v", expected, w.HeaderMap.Get("Content-Type"))
}
}
現在、depricateになっているので対象コードのコメントに沿って、Response.Header
を使いましょう。
// use the Response.Header map as returned by the Result method.
HeaderMap http.Header
handler_test.go
func TestHandler(t *testing.T) {
// httptestの準備
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/tests", nil)
TestHandler(w, r)
// 各種チェック
res := w.Result()
defer res.Body.Close()
// Content-Typeのチェック
if expected := "application/json; charset=utf-8"; res.Header.Get("Content-Type") != expected {
t.Errorf("unexpected response Content-Type, expected: %#v, but given #%v", expected, w.HeaderMap.Get("Content-Type"))
}
}
この例だと、w.HeaderMap
をres.Header
に書き換えるのみですね。
以上