gofiber: session

一,代码:

官网文档地址:

https://docs.gofiber.io/api/middleware/session

1,全局变量

package config

import (
	"github.com/gofiber/fiber/v2/middleware/session"
	"github.com/gofiber/fiber/v2/utils"
	"time"
)

var Store = session.New(session.Config{
	Expiration:   24 * time.Hour,
	KeyLookup:    "cookie:session_id",
	KeyGenerator: utils.UUIDv4,
})

2, 写入

func (dc *ArticleController) ListArticle(c *fiber.Ctx) error {
	sess, err := config.Store.Get(c)
	if err != nil {
		return c.SendString("session读取错误")
	}

	user:=c.Query("user")
	if user == "" {
		sess.Set("islogin", "no")
		sess.Set("name", "")
	} else {
		sess.Set("islogin", "yes")
		sess.Set("name", user)
	}
	username1 := sess.Get("name")
	fmt.Println("保存前:",username1)
	fmt.Println("保存前:",sess)
	if err := sess.Save(); err != nil {
		return c.SendString("session保存错误")
	}
    //保存后再次读取session
	sess, err = config.Store.Get(c)
	if err != nil {
		return c.SendString("session读取错误")
	}

	username := sess.Get("name")
	fmt.Println("保存后:",username)
	fmt.Println("保存后:",sess)

	myMap:=fiber.Map{}
	myMap["Title"] = "书店新上图书列表"
	myMap["SessionUser"] = username


	return c.Render("article/list", myMap)
}

3, 读取

func (dc *ArticleController) GetArticle(c *fiber.Ctx) error {
	sess, err := config.Store.Get(c)
	if err != nil {
		return c.SendString("session错误")
	}

	fmt.Println(sess)
    //读取单个value
	username := sess.Get("name")
	fmt.Println(username)
	//列出所有的key
	keys := sess.Keys()
	fmt.Println(keys)

	myMap:=fiber.Map{}

	myMap["Title"] = "书店新上图书列表"
	myMap["SessionUser"] = username
    return c.Render("article/info", myMap)
}

二,测试效果

写入到session

从session读取

 

posted @ 2024-11-23 09:06  刘宏缔的架构森林  阅读(3)  评论(0编辑  收藏  举报