从浏览器中获取cookie
程序员文章站
2022-06-11 22:30:20
...
从请求的首部获取cookie
语句r.Header[“Cookie”]返回了一个切片,这个切片包含了一个字符串,而这个字符串又包含了客户端发送的任意多个cookie。
package main
import (
"fmt"
"net/http"
)
func setCookie(w http.ResponseWriter, r *http.Request) {
c1 :=http.Cookie{
Name: "fu",
Value: "Go1",
HttpOnly: true,
}
c2 :=http.Cookie{
Name: "fu2",
Value: "Go2",
HttpOnly: true,
}
http.SetCookie(w,&c1)
http.SetCookie(w,&c2)
}
func getCookie(w http.ResponseWriter, r *http.Request) {
h :=r.Header["Cookie"]
fmt.Fprintln(w,h)
}
func main() {
server := http.Server{
Addr:"127.0.0.1:8080",
}
http.HandleFunc("/set_cookie", setCookie)
http.HandleFunc("/get_cookie", getCookie)
server.ListenAndServe()
}
使用Cookie方法和Cookies
Go语言为Request结构提供了一个Cookie方法,这个方法可以获取指定名字的cookie。如果指定的cookie不存在,那么方法将返回一个错误。因为Cookie方法只能获取单个cookie,所以如果想要同时获取多个cookie,就需要用到Request结构的Cookies方法:Cookies方法可以返回一个包含了所有cookie的切片
package main
import (
"fmt"
"net/http"
)
func setCookie(w http.ResponseWriter, r *http.Request) {
c1 :=http.Cookie{
Name: "fu",
Value: "Go1",
HttpOnly: true,
}
c2 :=http.Cookie{
Name: "fu2",
Value: "Go2",
HttpOnly: true,
}
http.SetCookie(w,&c1)
http.SetCookie(w,&c2)
}
func getCookie(w http.ResponseWriter, r *http.Request) {
c1,err :=r.Cookie("fu")
if err != nil {
fmt.Fprintln(w,"Cannot get the first cookie")
}
cs :=r.Cookies()
fmt.Fprintln(w,c1)
fmt.Fprintln(w,cs)
}
func main() {
server := http.Server{
Addr:"127.0.0.1:8080",
}
http.HandleFunc("/set_cookie", setCookie)
http.HandleFunc("/get_cookie", getCookie)
server.ListenAndServe()
}