0
0

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 1 year has passed since last update.

Golang + Ginのテスト内でセッションを保存する方法

Last updated at Posted at 2022-07-26

TL; DR

Golang + Ginを使ったリクエストのテスト中でセッションを保存する方法に多少苦戦したので紹介

結論

import (
	"net/http/httptest"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/sessions"
)

func SaveSession(recorder *httptest.ResponseRecorder, context *gin.Context, key string, value interface{}) {
	var store = sessions.NewCookieStore([]byte("secret"))
	session, _ := store.Get(context.Request, "session")
	session.Values[key] = value
	session.Save(context.Request, recorder)
}

使い方

import (
	"net/http"
	"net/http/httptest"

	"github.com/gin-gonic/gin"
)

func Router() *gin.Engine {
	r := gin.New()
	r.GET("/url", func(ctx *gin.Context) {
		ctx.Status(http.StatusOK)
	})
	return r
}

func (suite *Controller) TestIndexSuccess() {
	recorder := httptest.NewRecorder()
	context, _ := gin.CreateTestContext(recorder)
	userID := uint(1)
	router := s.Router()
	context.Request, _ = http.NewRequest("GET", "/url", nil)
	SaveSession(recorder, context, "session key", userID)
	router.ServeHTTP(recorder, context.Request)
	suite.Equal(http.StatusOK, recorder.Code)
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?