gin中设置和获取cookie

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

func main() {
	router := gin.Default()

	router.GET("/cookie", func(context *gin.Context) {
		// 获取cookie
		cookie, err := context.Cookie("gin_cookie")
		if err != nil {
			cookie = "NotSet"
			// 设置cookie
			// secure: 属性可防止信息在传递的过程中被监听捕获后导致信息泄露,如果设置为true,可以限制只有通过https访问时,才会将浏览器保存的cookie传递到服务端,如果通过http访问,不会传递cookie。
			// httpOnly: 属性可以防止程序获取cookie,如果设置为true,通过js等将无法读取到cookie,能有效的防止XSS攻击。
			context.SetCookie("gin_cookie", "123465", 60, "/", "127.0.0.1", false, true)
		}
		fmt.Println("cookie =", cookie)
		context.String(200, "ok")
	})

	router.Run()
}

  

posted @ 2021-10-28 14:50  专职  阅读(533)  评论(0编辑  收藏  举报