Go Web --- 使用cookie
设置cookie
package main import ( "net/http" ) func index(response http.ResponseWriter, request *http.Request) { c1 := http.Cookie{ Name: "first", Value: "this is the first cookie", HttpOnly: true, } c2 := http.Cookie{ Name: "first", Value: "this is the third cookie", HttpOnly: true, } // 方法一 //func (h Header) Set(key, value string) //设置cookie,set方法会覆盖已有项 //response.Header().Set("Set-Cookie", c1.String()) //func (h Header) Add(key, value string) //追加,并不会覆盖,如果之前没有此项,则会添加 //response.Header().Add("Set-Cookie", c2.String()) // 方法二 //func SetCookie(w ResponseWriter, cookie *Cookie) //虽然是set,但是不会覆盖,即使是Name相同,也不会覆盖,只是追加 http.SetCookie(response, &c1) http.SetCookie(response, &c2) } func main() { server := http.Server{ Addr: "127.0.0.1:8081", } http.HandleFunc("/index", index) server.ListenAndServe() }
推荐使用第二种方法:http.SetCookie(request,&c)
注意,如果使用response.Header().Set或者Add设置cookie时,key必须是Set-Cookie,否则设置的就不是cookie,而是header头部字段而已。
获取请求中的cookie
request.Header["Cookie"]
package main import ( "fmt" "net/http" ) func index(response http.ResponseWriter, request *http.Request) { c1 := http.Cookie{ Name: "first", Value: "this is the first cookie", HttpOnly: true, } c2 := http.Cookie{ Name: "second", Value: "this is the third cookie", HttpOnly: true, } http.SetCookie(response, &c1) http.SetCookie(response, &c2) } //获取cookie func getCookie(response http.ResponseWriter, request *http.Request) { cookie := request.Header["Cookie"]//注意键Cookie的首字母大写 fmt.Fprintln(response, cookie) //[first="this is the first cookie"; second="this is the third cookie"] } func main() { server := http.Server{ Addr: "127.0.0.1:8081", } http.HandleFunc("/index", index) http.HandleFunc("/test", getCookie) server.ListenAndServe() }
更简便的获取cookie
//获取cookie func getCookie(response http.ResponseWriter, request *http.Request) { first, _ := request.Cookie("third") cookies := request.Cookies() fmt.Fprintln(response, first, //first="this is the first cookie" first.Value, //this is the first cookie //first.Expires 、first.Name 、first.Domain ... cookies, //[first="this is the first cookie" second="this is the third cookie"] ) }
如需转载,请注明文章出处,谢谢!!!