使用go gin来操作cookie的讲解

今天小编就为大家分享一篇关于使用go gin来操作cookie的讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

准确地说, 这个标题是有问题的, go gin只能给浏览器返回操作cookie的指令, 真正执行cookie操作的是浏览器。 但广泛地来讲, 说go gin操作cookie, 也是可以的(间接操作)

来看go gin代码:

package main
import (
  "github.com/gin-gonic/gin"
)
func main() {
  router := gin.Default();
  router.GET("/read_cookie", func(context *gin.Context) {
    val, _ := context.Cookie("name")
    context.String(200, "Cookie:%s", val) 
  })
  router.GET("/write_cookie", func(context *gin.Context) {
    context.SetCookie("name", "Shimin Li", 10, "/", "localhost", false, true)
  })
  router.GET("/clear_cookie", func(context *gin.Context) {
    context.SetCookie("name", "Shimin Li", -1, "/", "localhost", false, true)
  })
  router.Run(":8080")
}

开启服务。浏览器端执行读取、写入、清除的操作分别是:

http://localhost:8080/read_cookie

http://localhost:8080/write_cookie

http://localhost:8080/clear_cookie

自己玩了一下, OK.

不多说。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对神马文库的支持。如果你想了解更多相关内容请查看下面相关链接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章