總所周知,http是無狀態協議,即http的每次請求都是獨立的,它不會受之前的請求影響,在這種情況下,對於服務器而言每次請求都全新的,所以服務器處理之前請求參數的數據都不會保留,會話中產生的數據又是我們需要保存的,也就是說要“保持狀態”。因此Cookie就是在這樣一個場景下誕生。
http中的cookie是由服務器產生,發送給瀏覽器,當瀏覽器第二次訪問統一網站時,攜帶cookie信息發送給服務器,服務器解析cookie中的信息,借此維護用戶跟服務器會話中的狀態。
總結一下Cookie的特點:
- 瀏覽器發送請求的時候,自動把攜帶該站點之前存儲的Cookie信息。
- Cookie是一組鍵值對(key-val),可以設置其屬性,例如keepalive、path等等
- 服務端可以設置Cookie數據。
- Cookie是針對單個域名的,不同域名之間的Cookie是獨立的。
- Cookie數據可以配置過期時間,過期的Cookie數據會被系統清除。
go http中的Cookie
type Cookie struct { Name string Value string Path string // optional Domain string // optional Expires time.Time // optional RawExpires string // for reading cookies only // MaxAge=0 means no 'Max-Age' attribute specified. // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0' // MaxAge>0 means Max-Age attribute present and given in seconds MaxAge int Secure bool HttpOnly bool SameSite SameSite Raw string Unparsed []string // Raw text of unparsed attribute-value pairs }
go http中設置Cookie
func SetCookie(w ResponseWriter, cookie *Cookie)
w是請求的響應信息。
go http 操作Cookie:
package main import ( "net/http" ) func SayOk(w http.ResponseWriter, r *http.Request) { cookie := &http.Cookie{ Name: "fly", Value: "123456", MaxAge: 10, } cookie2 := &http.Cookie{ Name: "cc", Value: "123456", Path: "/aabb", MaxAge: 10, } http.SetCookie(w, cookie) http.SetCookie(w, cookie2) w.Write([]byte("你好,fly")) } func main() { http.HandleFunc("/", SayOk) http.ListenAndServe(":9999", nil) }
關於gin框架設置Cookie
package main import ( "github.com/gin-gonic/gin" "net/http" ) func main() { e := gin.Default() e.GET("/", func(c *gin.Context) { c.SetCookie("username", "fly", 0, "", "", false, false) //c.Set("name","aaaabbbb") //c.JSON(http.StatusOK, "你好,世界") c.Redirect(http.StatusMovedPermanently, "/get") }) e.GET("/get", func(c *gin.Context) { c.SetCookie("username", "fly", 0, "", "", false, false) c.JSON(http.StatusOK, "重定向:你好,世界") }) e.Run(":9999") }
Session
Cookie雖然在一定程度上解決了“保持狀態”的需求,但是由於Cookie本身最大支持4096字節,以及Cookie本身保存在客戶端,可能被攔截或竊取,因此就需要有一種新的東西,它能支持更多的字節,並且他保存在服務器,有較高的安全性。這就是session。
session 其實也是Cookie的數據,但是它具有唯一標識的特性即sessionid,瀏覽器每次請求的時候都攜帶cookie包括session ID,這樣一組請求就關聯起來了成為了一個session
go http並沒有實現session的代碼,可能session就是Cookie操作,所以就需要自己實現
注意:當瀏覽器關閉了一個session的時候,服務器並不知道,所以這是就需要瀏覽器發送通知讓session老化