【问题标题】:How to expand session.Value with String如何用字符串扩展 session.Value
【发布时间】:2018-11-26 02:01:10
【问题描述】:

我正在使用 Gorilla/Sessions。

我有一个模板页面,用户可以在其中选择不同的设备。 如果他使用每个设备下的提交按钮之一,我的控制器功能应该将 id 值添加到我现有的会话值中。

  func Cart(w   http.ResponseWriter,    r   *http.Request)  {   

data := CartData{ 
    Name: "Cart",
    Equipment: model.GetEquipment(model.Db),
    Pages: []Page{
        {
            Title: "Meine Geräte", 
            Active: false,
            Link: "/my-equipment",
        },
        {
            Title: "Equipment", 
            Active: false,
            Link: "/equipment",
        },
        {
            Title: "Logout",
            Active: false,
            Link: "/logout",
        },
    },

}

    equipment,_ := model.GetEquipmentByID(r.FormValue("id"))
    session, _ := store.Get(r, "cookie-name")

    Strings := strconv.Itoa(equipment.ID)
    fmt.Println(Strings)
    StringsWithComma := Strings + ","
    session.Values["EquipmentIDs"] = session.Values["EquipmentIDs"] + StringsWithComma // THIS CODE LINE DOES NOT WORK, I want to expand "EquipmentIDs" with the new ID

tmpl:= template.Must(template.ParseFiles("template/base_user.html", "template/cart.html"))
tmpl.ExecuteTemplate(w, "base", data)
}
}

示例:用户正在访问我的设备页面。他使用 id=2 的提交按钮 SessionValue["EquipmentIDs"] 现在应该是 = "2"。 之后,用户再次访问设备页面并使用 id=6 的提交按钮。 现在 SessionValue 应该是 = "2,6"

我整天都在关注这个问题,无法再进一步 如果您有问题或想查看我的代码的其他部分,请随时提问 提前致谢

【问题讨论】:

  • 它可能看起来很愚蠢,但session.Save(r,w) 行在哪里?
  • 是的,没错。这不是唯一的错误

标签: session go web cookies gorilla


【解决方案1】:

我认为你应该从会话中获取原始设备值,结合用户点击的设备ID并保存到会话中以供下次请求。

我将您的代码更新如下:

// ...
equipment, _ := model.GetEquipmentByID(r.FormValue("id"))
session, _ := store.Get(r, "cookie-name")

equipmentIdsStr := strconv.Itoa(equipment.ID)

if original, exist := session.Values["EquipmentIDs"]; exist {
    equipmentIdsStr = fmt.Sprintf("%v,%v", original, equipmentIdsStr)
}

session.Values["EquipmentIDs"] = equipmentIdsStr

//You have to save your updated session value
session.Save(r, w)
// ...

希望对您有所帮助。

【讨论】:

  • 无效操作:第 410 行的 original + "," (不匹配类型接口 () 和字符串)。(设备IdsStr = original + "," + equipmentIdsStr)
  • 将其更改为 deviceIdsStr = original.(string) + "," + equipmentIdsStr。现在可以了,非常感谢
  • @ChristopherG1994 谢谢。我刚刚更新为使用fmt.Sprintf 以更好地从interface 转换为string。
猜你喜欢
  • 2019-05-27
  • 1970-01-01
  • 2015-08-29
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
相关资源
最近更新 更多