从go服务端"设置cookie"来看cookie的本质

版权声明:本文为博主原创文章,转载时请务必注明本文地址, 禁止用于任何商业用途, 否则会用法律维权。 https://blog.csdn.net/stpeace/article/details/82717979

       cookie到底是什么, 很多地方越说越乱,玄乎其玄, 其实,很简单, 一起来看看。

       go 服务端的代码为:

package main

import "net/http"

func main()  {
   http.HandleFunc("/writecookie", WriteCookie)
   http.ListenAndServe("localhost:8080", nil)
}

func WriteCookie(w http.ResponseWriter, r *http.Request)  {
   cookie := http.Cookie{Name:"name", Value:"Shimin Li", Path:"/", MaxAge:60}
   http.SetCookie(w, &cookie)
   w.Write([]byte("write cookie ok"))
}

        go run s.go跑起来。

       

       在chrome浏览器中执行: http://localhost:8080/writecookie,  触发go服务执行设置cookie的动作, 浏览器收到这个信息后, 真正执行设置cookie,  在chrome中可查(chrome://settings/content/cookies目录中的localhost域名中查), 如下:

        可以看到,过期时间是60s, 60s后再次查的时候, 就没有name对应的cookie项了。

        我们等cookie过期消失, 然后再来玩抓包。 

        好,现在没有name对应的cookie了, 我们连续两次执行:http://localhost:8080/writecookie, 服务端tcpdump抓包,两次的请求和响应依次如下:

GET /writecookie HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: xxxxxx
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
HTTP/1.1 200 OK
Set-Cookie: name="Shimin Li"; Path=/; Max-Age=60
Date: Sat, 15 Sep 2018 13:41:17 GMT
Content-Length: 15
Content-Type: text/plain; charset=utf-8
GET /writecookie HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: xxxxxx
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
Cookie: name="Shimin Li"
HTTP/1.1 200 OK
Set-Cookie: name="Shimin Li"; Path=/; Max-Age=60
Date: Sat, 15 Sep 2018 13:41:21 GMT
Content-Length: 15
Content-Type: text/plain; charset=utf-8

       可以看到,第一次请求时, 浏览器发出的请求中不带cookie, 因为浏览器压根就没有这项cookie, 在go服务端的回包中携带了Set-Cookie首部, 浏览器收到这个信息后,将其写入到浏览器本地, 形成cookie.

       第二次请求时(因cookie的过期时间设置为了60s, 故必须在60s内发起第二次请求), 此时, 浏览器的http请求中自动携带了cookie信息,go服务端也能收到这个信息。

   

       由此可见, cookie不过是浏览器端的一个环境变量而已, 仅此而已。cookie值存在于浏览器所在的本地电脑中。 而所谓的服务端设置cookie, 其实是服务端给浏览器发送对应的设置cookie信息, 由浏览器来真正执行设置cookie的操作, 存于本地电脑磁盘中。

       别扯其他的。

       

猜你喜欢

转载自blog.csdn.net/stpeace/article/details/82717979
今日推荐