LoginSignup
0

More than 5 years have passed since last update.

Go1.11からnet/http/httptestのResponseRecorder.HeaderMapがdepricatedになったので、Response.Headerを使ったほうがいい

Last updated at Posted at 2018-08-29

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.HeaderMapres.Headerに書き換えるのみですね。

以上

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
0