Go語言cookie的基本操作


cookie數據結構介紹

 

cookie數據結構介紹

a. Expires,cookie過期時間,使用絕對時間。比如2018/10/10 10:10:10
b. MaxAge,cookie過期時間,使用相對時間,比如300s
c. Secure屬性,是否需要安全傳輸,為true時只有https才會傳輸該cookie
Go語言cookie的基本操作
d. HttpOnly屬性,為true時,不能通過js讀取該cookie的值

 

golang讀取cookie

a. 讀取單個cookie, http.Request.Cookie(key string)

b. 讀取所有cookie, http.Request.Cookies()

 

golang設置cookie

a. cookie := http.Cookie{Name: "username", Value: "astaxie", Expires: expiration}
b. http.SetCookie(w, &cookie)

 

package main

import (
    "fmt"
    "net/http"
)

func indexHandle(w http.ResponseWriter, r *http.Request) {

    /*cookies := r.Cookies()
    for index, cookie := range cookies {
        fmt.Printf("index:%d cookie:%#v\n", index, cookie)
    }*/
    c, err := r.Cookie("sessionid")
    fmt.Printf("cookie:%#v, err:%v\n", c, err)

    cookie := &http.Cookie{
        Name:   "sessionid",
        Value:  "lkjsdfklsjfklsfdsfdjslf",
        MaxAge: 3600,
        Domain: "localhost",
        Path:   "/",
    }

    http.SetCookie(w, cookie)

    //在具體數據返回之前設置cookie,否則cookie種不上
    w.Write([]byte("hello"))
}

func main() {
    http.HandleFunc("/", indexHandle)
    http.ListenAndServe(":9090", nil)
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM