LoginSignup
0
1

More than 1 year has passed since last update.

Go/Gin sessionsで構造体の受け渡しについて

Last updated at Posted at 2022-12-16

Gin勉強の備忘録

今回Webアプリケーション開発中にsessionsでの構造体の受け渡しで躓いた

sessionsのインストール

"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"

サンプルコード

main.go
package main

import (
	"net/http"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
)

type User struct {
	ID   int
	Name string
}

func main() {
	router := gin.Default()
	store := cookie.NewStore([]byte("secret"))
	router.Use(sessions.Sessions("mysession", store))
	router.LoadHTMLGlob("views/*")

	router.GET("/", func(ctx *gin.Context) {
		session := sessions.Default(ctx)

		//文字列の登録
		email := "abc@aaa.com"
		session.Set("email", email)
		//保存
		session.Save()
		//構造体の登録
		user := User{ID: 1, Name: "Foo"}
		session.Set("user", user)
		//保存
		session.Save()

		ctx.HTML(http.StatusOK, "index.html", nil)
	})

	router.GET("/session", func(ctx *gin.Context) {
		session := sessions.Default(ctx)
		//文字列の受け取り
		email, _ := session.Get("email").(string)
		//構造体の受け取り
		user, _ := session.Get("user").(User)

		ctx.HTML(http.StatusOK, "session.html", gin.H{
			"email": email,
			"user":  user,
		})
	})

	router.Run()
}

session.Set("キー値", 値)で値の設定後、session.Save()で保存
  ※session.Save()を使わないと値をセットできない
*** := session.Get("キー値")で値の取得
interface型で受け取るため、.(型名)をつける

デバッグ実行結果

Screen Shot 2022-12-16 at 16.29.12.png

email(string)は取得できているが、user(構造体)が取得できていない。

解決策

〜現在模索中

大替手段

データベースを絡めているなら、ID等渡してSELECT文で構造体を引っ張ってくるとか

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