這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
合理的使用cookie可以極大的提高網站的使用者體驗,這一篇文章主要來討論一下,go中是如何處理cookie的。
聲明
Go語言中通過net/http包中的SetCookie來設定:
//設定cookie的方法聲明http.SetCookie(w ResponseWriter, cookie *Cookie)//Cookie的聲明type Cookie struct { Name string Value string Path string Domain string Expires time.Time RawExpires string // 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 Raw string Unparsed []string // Raw text of unparsed attribute-value pairs }
設定cookie的方法(寫在Index方法中)
tNow := time.Now()cookie := http.Cookie{Name: "username", Value: "BCL", Expires: tNow.AddDate(1, 0, 0)}http.SetCookie(w, &cookie)
運行一下,在瀏覽器中查看要求標頭,如:
cookie已經被成功設定.
擷取cookie的方法
獲得cookie的方法也很簡單:
username, err := r.Cookie("username")
需要注意的是r.Cookie(“username”)並不會直接返回username對應的字串類型的值
而是返回一個新的cookie struct,用來儲存username對應的值
現在將這兩步操作合并到一起,寫一個完整的處理cookie的樣本:
//讀取cookie,並做出相應的反饋username, err := r.Cookie("username")fmt.Println(username, err)if err != nil { fmt.Println("No Cookie", err)} //判斷是否已經設定了cookieif username == nil { //設定cookie tNow := time.Now() //設定cookie,有效期間為一年 cookie := http.Cookie{Name: "username", Value: "BCL", Expires: tNow.AddDate(1, 0, 0)} http.SetCookie(w, &cookie)} else { data["visited"] = "歡迎回來 " + username.Value}
運行一下,我們來運行一下看一下效果:
第一次訪問:
第二次訪問