4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Golang]HTTPTESTレスポンスのCookieの値を取得する

Last updated at Posted at 2019-09-25

概要

Goのハンドラなどに対するHTTPのテストを行う際に、レスポンスのCookieの値を取り出す方法メモです。

事前知識

参考にした主な記事など

内容

Cookieを返すだけのHogeHandler関数に対して、Cookieの値を取得して表示するテストを書きます。

main.go
package main

import (
	"net/http"
)

func HogeHandler(w http.ResponseWriter, r *http.Request) error {
	http.SetCookie(w, &http.Cookie{
		Name:  "hoge",
		Value: "hogevalue",
	})
	return nil
}
main_test.go
package main

import (
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestHogeHandler(t *testing.T) {
	req := httptest.NewRequest("GET", "/", nil)
	resp := httptest.NewRecorder()
	HogeHandler(resp, req)

	// ここでCookieをパースする
	parser := &http.Request{Header: http.Header{"Cookie": resp.Header()["Set-Cookie"]}}
	hogeCookie, _ := parser.Cookie("hoge")

	t.Log(hogeCookie.Value)
}

Cookie取得部分では、http.Requestを経由してCookie関数を利用することで、Cookieをパースして取得することができます。
本音を言うとhttptest.ResponseRecorderにCookie関数があってほしい...笑
ちなみにパースする必要がないならresp.Header()["Set-Cookie"]で取得できます。
HeaderMap関数は非推奨になったらしいです。

実行&出力

テスト実行

$ go test -v path/to/dir

出力結果

=== RUN   TestHogeHandler
--- PASS: TestHogeHandler (0.00s)
    main_test.go:17: hogevalue
PASS

参考

Jonny Reeves – Testing Setting HTTP Cookies in Go
http - The Go Programming Language
httptest - The Go Programming Language
testing - The Go Programming Language

最後に

記事に間違いや不明な点があれば遠慮なくご指摘ください。

4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?