在Gin中使用Cookie
下面代码是如何使用Cookie的样例,包括创建Cookie、获取Cookie和删除Cookie。
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/set-cookie", func(ctx *gin.Context) {
ctx.SetCookie("sessionid", "fuck cookie", 3600, "/", "localhost", false, false)
ctx.JSON(http.StatusOK, gin.H{
"msg": "set-cookie ok",
})
})
router.GET("/get-cookie", func(ctx *gin.Context) {
val, err := ctx.Cookie("sessionid")
if err == nil {
ctx.JSON(http.StatusOK, gin.H{
"msg": fmt.Sprintf("get cookie :sessionid=%v", val),
})
} else {
ctx.JSON(http.StatusOK, gin.H{
"msg": fmt.Sprintf("get cookie error:%v", err),
})
}
})
router.GET("/del-cookie", func(ctx *gin.Context) {
ctx.SetCookie("sessionid", "", -1, "/", "localhost", false, false)
ctx.JSON(http.StatusOK, gin.H{
"msg": "del-cookie ok",
})
})
if err := router.Run(":8001"); err != nil {
panic(err)
}
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/289667.html