首页 > 技术文章 > Go语言cookie的基本操作

sunlong88 2019-11-30 16:50 原文

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)
}

 

推荐阅读