Cookie
package main
import (
"github.com/gin-gonic/gin"
"fmt"
)
func main() {
// 1.创建路由
// 默认使用了2个中间件Logger(), Recovery()
r := gin.Default()
// 服务端要给客户端cookie
r.GET("cookie", func(c *gin.Context) {
// 获取客户端是否携带cookie
cookie, err := c.Cookie("key_cookie")
if err != nil {
cookie = "NotSet"
// 给客户端设置cookie
// maxAge int, 单位为秒
// path,cookie所在目录
// domain string,域名
// secure 是否智能通过https访问
// httpOnly bool 是否允许别人通过js获取自己的cookie
c.SetCookie("key_cookie", "value_cookie", 60, "/",
"localhost", false, true)
}
fmt.Printf("cookie的值是: %s\n", cookie)
})
r.Run(":8000")
}
Session
First we initialize a session store calling NewCookieStore()
and passing a secret key used to authenticate the session. Inside the handler, we call store.Get()
to retrieve an existing session or create a new one. Then we set some session values in session.Values, which is a map[interface{}]interface{}
. And finally we call session.Save()
to save the session in the response.
import (
"net/http"
"github.com/gorilla/sessions"
)
// Note: Don't store your key in your source code. Pass it via an
// environmental variable, or flag (or both), and don't accidentally commit it
// alongside your code. Ensure your key is sufficiently random - i.e. use Go's
// crypto/rand or securecookie.GenerateRandomKey(32) and persist the result.
var store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))
func MyHandler(w http.ResponseWriter, r *http.Request) {
// Get a session. We're ignoring the error resulted from decoding an
// existing session: Get() always returns a session, even if empty.
session, _ := store.Get(r, "session-name")
// Set some session values.
session.Values["foo"] = "bar"
session.Values[42] = 43
// Save it before we write to the response/return from the handler.
err := session.Save(r, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
应用
package main
import (
"github.com/gin-gonic/gin"
"github.com/gorilla/sessions"
)
var store = sessions.NewCookieStore([]byte("session"))
func main() {
r := gin.Default()
r.GET("/cookie", func(this *gin.Context) {
this.SetCookie("name", "zhangsan", 60*60*24, "/", "", false, true)
this.JSON(200, gin.H{"cookie": true})
})
r.GET("/session", func(this *gin.Context) {
session, _ := store.Get(this.Request, "session-name")
session.Values["captcha"] = "9safji3w9jsal"
session.Save(this.Request, this.Writer)
this.JSON(200, gin.H{"session": true})
})
r.Run(":8090")
}