Golang gin框架生成cookie的问题

huangapple go评论81阅读模式
英文:

Golang gin framework cookie generating issue

问题

这是我的代码,我从go-gin框架的文档中复制过来的。我的问题是当createCookie函数被调用时,它返回"NotSet",我必须运行相同的API回调来获取一个cookie。

// createCookie接受gin上下文c并创建cookie
func createCookie(c *gin.Context) (string, error) {
    cookie, err := c.Cookie("device")

    if err != nil {
        cookie = "NotSet"
        c.SetCookie("device", "test", 3600, "/", os.Getenv("AUTH_DOMAIN"), true, true)
    }

    return cookie, nil
}
英文:

This is my code and I copy it from the go-gin framework documents, My problem is when createCookie function hits it returns "NotSet" and I have to run same API callback to get a cookie.

// createCookie accepts c as gin context and create cookies
func createCookie(c *gin.Context) (string, error) {
	cookie, err := c.Cookie("device")

	if err != nil {
		cookie = "NotSet"
		c.SetCookie("device", "test", 3600, "/", os.Getenv("AUTH_DOMAIN"), true, true)
	}

	return cookie, nil
}

答案1

得分: 1

// createCookie接受gin上下文c并创建cookie
func createCookie(c *gin.Context) (string, error) {
    cookie, err := c.Cookie("device")

    if err != nil {
        // 用你的初始值替换它
        cookie = "NotSet"
        c.SetCookie("device", cookie, 3600, "/", os.Getenv("AUTH_DOMAIN"), true, true)
    }

    return cookie, nil
}
英文:
// createCookie accepts c as gin context and create cookies
func createCookie(c *gin.Context) (string, error) {
    cookie, err := c.Cookie("device")

    if err != nil {
        // Replae it with your initial value
        cookie = "NotSet"
        c.SetCookie("device", cookie, 3600, "/", os.Getenv("AUTH_DOMAIN"), true, true)
    }

    return cookie, nil
}

huangapple
  • 本文由 发表于 2021年10月19日 00:07:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/69619222.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定