Cookie

  1. package main
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "fmt"
  5. )
  6. func main() {
  7. // 1.创建路由
  8. // 默认使用了2个中间件Logger(), Recovery()
  9. r := gin.Default()
  10. // 服务端要给客户端cookie
  11. r.GET("cookie", func(c *gin.Context) {
  12. // 获取客户端是否携带cookie
  13. cookie, err := c.Cookie("key_cookie")
  14. if err != nil {
  15. cookie = "NotSet"
  16. // 给客户端设置cookie
  17. // maxAge int, 单位为秒
  18. // path,cookie所在目录
  19. // domain string,域名
  20. // secure 是否智能通过https访问
  21. // httpOnly bool 是否允许别人通过js获取自己的cookie
  22. c.SetCookie("key_cookie", "value_cookie", 60, "/",
  23. "localhost", false, true)
  24. }
  25. fmt.Printf("cookie的值是: %s\n", cookie)
  26. })
  27. r.Run(":8000")
  28. }

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.

  1. import (
  2. "net/http"
  3. "github.com/gorilla/sessions"
  4. )
  5. // Note: Don't store your key in your source code. Pass it via an
  6. // environmental variable, or flag (or both), and don't accidentally commit it
  7. // alongside your code. Ensure your key is sufficiently random - i.e. use Go's
  8. // crypto/rand or securecookie.GenerateRandomKey(32) and persist the result.
  9. var store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))
  10. func MyHandler(w http.ResponseWriter, r *http.Request) {
  11. // Get a session. We're ignoring the error resulted from decoding an
  12. // existing session: Get() always returns a session, even if empty.
  13. session, _ := store.Get(r, "session-name")
  14. // Set some session values.
  15. session.Values["foo"] = "bar"
  16. session.Values[42] = 43
  17. // Save it before we write to the response/return from the handler.
  18. err := session.Save(r, w)
  19. if err != nil {
  20. http.Error(w, err.Error(), http.StatusInternalServerError)
  21. return
  22. }
  23. }

应用

  1. package main
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/gorilla/sessions"
  5. )
  6. var store = sessions.NewCookieStore([]byte("session"))
  7. func main() {
  8. r := gin.Default()
  9. r.GET("/cookie", func(this *gin.Context) {
  10. this.SetCookie("name", "zhangsan", 60*60*24, "/", "", false, true)
  11. this.JSON(200, gin.H{"cookie": true})
  12. })
  13. r.GET("/session", func(this *gin.Context) {
  14. session, _ := store.Get(this.Request, "session-name")
  15. session.Values["captcha"] = "9safji3w9jsal"
  16. session.Save(this.Request, this.Writer)
  17. this.JSON(200, gin.H{"session": true})
  18. })
  19. r.Run(":8090")
  20. }