使用golang的標準庫搭建網站--5.處理COOKIE

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

合理的使用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}

運行一下,我們來運行一下看一下效果:
第一次訪問:

第二次訪問

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.