使用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.

不多說。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對神馬文庫的支持。如果你想了解更多相關內容請查看下面相關鏈接

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