golang封裝cookie
來源:互聯網
上載者:User
```gopackage libimport ("net/http""time")//用來做cookie 處理type CookieHandle struct {Http_writer http.ResponseWriter //主要用來寫入頭部Http_request *http.Request //主要用來擷取頭部資訊Expires time.Duration //到期時間 納秒}//cookie 初始化func CookieInit(w http.ResponseWriter, req *http.Request, expire string) *CookieHandle {//cookie 初始化cookie := new(CookieHandle)cookie.Http_writer = wcookie.Http_request = reqcookie.Expires = cookie.expireDuration(expire)return cookie}//擷取cookiefunc (this *CookieHandle) GetCookie(key string) string {cookie, cookie_err := this.Http_request.Cookie(key)if cookie_err != nil {return ""}return cookie.Value}func (this *CookieHandle) expireDuration(expire string) time.Duration {expire_time, err := time.ParseDuration(expire)//如果解析有效時時間失敗 不設定有效時間if err != nil {return 0}return expire_time}//設定cookiefunc (this *CookieHandle) SetCookie(key, val string, expire ...string) {//建立 http.cookie 指標cookie := new(http.Cookie)cookie.Name = keycookie.Value = val//如果有傳遞逾時時間 重新設定逾時時間if len(expire) > 0 {this.Expires = this.expireDuration(expire[0])}//如果不設定 到期時間 不賦值if this.Expires != 0 {cookie.Expires = time.Now().Add(this.Expires)}//調用http 包 進行設定cookie 大致是 講cookie 構造體的資料 產生 string header().set()http.SetCookie(this.Http_writer, cookie)}//刪除cookiefunc (this *CookieHandle) DelCookie(key string) {cookie := new(http.Cookie)cookie.Name = key//講到期時間改為 -1 s 就可以清空對應的cookiecookie.Expires = time.Now().Add(this.expireDuration("-1s"))http.SetCookie(this.Http_writer, cookie)}調用代碼package mainimport ("bbs/lib""net/http")func main() {http.HandleFunc("/", test)http.ListenAndServe(":8080", nil)}func test(w http.ResponseWriter, req *http.Request) { cookie := lib.CookieInit(w, req, "1m")cookie.SetCookie("test", "xiaochuan")w.Write([]byte(cookie.GetCookie("test")))}寫個這玩意也是頭痛萬分啊。還是太渣```71 次點擊