Go cookie 的简单测试

 

golang在服务端生成cookie与读取

如果是用gin包,使用gin.context可以直接设置cookie, 具体内容如下:

 

package main

 

import "github.com/gin-gonic/gin"

 

func main() {

r := gin.Default()

r.GET("/ping", func(c *gin.Context) {

c.SetCookie("testC1", "my1Cookie", 3600, "/", "localhost", false, true)

c.SetCookie("testC2", "my2Cookie", 3600, "/", "172.16.0.49", false, true)

c.SetCookie("testC3", "my3Cookie", 3600, "/", "172.16.0.49:1516", false, true)

c.SetCookie("testC4", "my4Cookie", 3600, "/p1", "172.16.0.49", false, true)

c.SetCookie("testC5", "my5Cookie", 3600, "/p1/p2", "172.16.0.49", false, true)

c.SetCookie("testC6", "my6Cookie", 3600, "/", "172.16.0.49", true, true)

c.JSON(200, gin.H{

"message": "pong",

})

})

r.Run(":4444")

}

 

通过chrome://settings/siteData查看cookie, 可以查看到cookie信息的有testC2、testC3、testC4、testC5,其他的看不到是因为testC1设置的domain参数为localhost,testC6设置的secure参数为true,只有https服务才能获取该cookie。httpOnly为true则表示只有服务端能够访问cookie,js等脚本语言不能够直接读取浏览器里面的cookie。

 

package main

 

import (

"fmt"

"github.com/gin-gonic/gin"

)

 

func main() {

r := gin.Default()

r.GET("/testGetCookie", func(c *gin.Context) {

c1,_:=c.Cookie("testC1")

c2,_:=c.Cookie("testC1")

 

})

r.Run(":16666") }

使用上述代码,通过ip:16666/testGetCookie能够获取到的cookie是testC2、testC3, testC1获取不到是因为设置的域是localhost,访问ip不能获取localhost下面的cookie。testC4、testC5访问不到是因为该cookie的path设置在/p1,/p1/p2 下面,只有指定的路由下面才能够访问到。

通过localhost:1666/testGetCookie能够获取到的cookie数量为0,原因是写入cookie的时候是通过ip:4444写入的,testC1并没有写入cookie。

通过ip:16666/p1/p2能够获取到的cookie是testC2、testC3、testC4、testC5,testC1访问不到的原因同上,testC6访问不到的原因同上。

以上实验说明,设置cookie的path可以是任何path,要想访问cookie, 必须在cookie的path开头的路径才能访问,例如testC2的path是”/”,所以只要访问了该ip的任何借口都可以获取cookie,cookie的domain属性的端口号没有生效。

cookie的清除

package main

 

import (

"github.com/gin-gonic/gin"

)

 

func main() {

r := gin.Default()

r.GET("/p1", func(c *gin.Context) {

c.SetCookie("testC1", "my1Cookie", -1, "/", "localhost", false, true)

c.SetCookie("testC2", "my2Cookie", -1, "/", "172.16.0.49", false, true)

c.SetCookie("testC3", "my3Cookie", -1, "/", "172.16.0.49:1516", false, true)

c.SetCookie("testC4", "my4Cookie", -1, "/p1", "172.16.0.49", false, true)

c.SetCookie("testC5", "my5Cookie", -1, "/p1/p2", "172.16.0.49", false, true)

c.SetCookie("testC6", "my6Cookie", -1, "/", "172.16.0.49", true, true)

})

r.Run(":17777") // listen and serve on 0.0.0.0:8080

}

通过测试,通过ip:port/* 都可以请求domain域属性为“/”的所有cookie。

通过测试,服务端可以设置任意路径的cookie,但是读取只能是通过对应的路径读取。

cookie的安全机制

设置httponly可以防止cookie被js读取,通过配置secure=ture可以保证只有https服务能够拿到cookie, 并且不能够直接通过浏览器查看cookie。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值