http 是无状态协议,服务器不能记录浏览器的访问状态,也就是说服务器不
能区分中两次请求是否由一个客户端发出。这样的设计严重阻碍的 web 程序的设计。
如:在我们进行网购时,买了一条裤子,又买了一个手机。由于 http 协议是无状态的,
如果不通过其他手段,服务器是不能知道用户到底买了什么。而 cookie 就是解决方案
之一。
cookie 实际上就是服务器保存在浏览器上的一段信息。浏览器有了 cookie 之后,
每次向服务器发送请求时都会同时将该信息发送给服务器,服务器收到请求后,就可以
根据该信息处理请求。
func handler(w http.responsewriter, r *http.request) { cookie1 := http.cookie{ name: "user1", value: "admin", httponly: true, } cookie2 := http.cookie{ name: "user2", value: "superadmin", httponly: true, } //将 cookie 发送给浏览器,即添加第一个 cookie w.header().set("set-cookie", cookie1.string()) //再添加一个 cookie w.header().add("set-cookie", cookie2.string()) }
浏览器响应报文中的内容
http/1.1 200 ok set-cookie: user1=admin; httponly set-cookie: user2=superadmin; httponly date: sun, 12 aug 2018 07:24:49 gmt content-length: 0 content-type: text/plain; charset=utf-8
get /cookie http/1.1 host: localhost:8080 connection: keep-alive upgrade-insecure-requests: 1 user-agent: mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/67.0.3396.62 safari/537.36 accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/ apng,*/*;q=0.8 accept-encoding: gzip, deflate, br accept-language: zh-cn,zh;q=0.9,en-us;q=0.8,en;q=0.7 cookie: user1=admin; user2=superadmin
将 1)中的代码进行修改
func handler(w http.responsewriter, r *http.request) { cookie1 := http.cookie{ name: "user1", value: "admin", httponly: true, } cookie2 := http.cookie{ name: "user2", value: "superadmin", httponly: true, } http.setcookie(w, &cookie1) http.setcookie(w, &cookie2) }
由于我们在发送请求时 cookie 在请求头中,所以我们可以通过 request 结构中的
header 字段来获取 cookie
func handler(w http.responsewriter, r *http.request) { //获取请求头中的 cookie cookies := r.header["cookie"] fmt.fprintln(w, cookies) }
[user1=admin; user2=superadmin]
cookie 默认是会话级别的,当关闭浏览器之后 cookie 将失效,我们可以通过 cookie
结构的 maxage 字段设置 cookie 的有效时间
func handler(w http.responsewriter, r *http.request) { cookie := http.cookie{ name: "user", value: "persistadmin", httponly: true, maxage: 60, } //将 cookie 发送给浏览器 w.header().set("set-cookie", cookie.string()) }
http/1.1 200 ok set-cookie: user=persistadmin; max-age=60; httponly date: sun, 12 aug 2018 07:32:57 gmt content-length: 0 content-type: text/plain; charset=utf-8
使用 cookie 有一个非常大的局限,就是如果 cookie 很多,则无形的增加了客户
端与服务端的数据传输量。而且由于浏览器对 cookie 数量的限制,注定我们不能再
cookie 中保存过多的信息,于是 session 出现。
session 的作用就是在服务器端保存一些用户的数据,然后传递给用户一个特殊
的 cookie,这个 cookie 对应着这个服务器中的一个 session,通过它就可以获取到保
存用户信息的 session,进而就知道是那个用户再发送请求。
如对本文有疑问, 点击进行留言回复!!
网友评论