设置cookie
c.SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool
// 第一个参数 key
// 第二个参数 value
// 第三个参数 过期时间.如果只想设置 Cookie 的保存路径而不想设置存活时间,可以在第三个
// 参数中传递 nil
// 第四个参数 cookie 的路径
// 第五个参数 cookie 的路径 Domain 作用域 本地调试配置成 localhost , 正式上线配置成域名
// 第六个参数是 secure ,当 secure 值为 true 时,cookie 在 HTTP 中是无效,在 HTTPS 中才有效
// 第七个参数 httpOnly,是微软对 COOKIE 做的扩展。如果在 COOKIE 中设置了“httpOnly”属性,
// 则通过程序(JS 脚本、applet 等)将无法读取到 COOKIE 信息,防止 XSS 攻击产生
获取cookie
cookie, err := c.Cookie("name")
Demo
package main
import ( "gin_demo/models"
"html/template"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.SetFuncMap(template.FuncMap{ "unixToDate": models.UnixToDate, })
r.GET("/", func(c *gin.Context) {
c.SetCookie("usrename", "张三", 3600, "/", "localhost", false, true)
c.String(200, "首页")
})
r.GET("/user", func(c *gin.Context) {
username, _ := c.Cookie("usrename")
c.String(200, "用户-"+username)
})
r.Run(":8080")
}
二级域名共享 cookie
c.SetCookie("usrename", "张三", 3600, "/", ".itying.com", false, true)