gpt4 book ai didi

session - 如何使用 String 扩展 session.Value

转载 作者:数据小太阳 更新时间:2023-10-29 03:22:39 24 4
gpt4 key购买 nike

我正在使用 Gorilla/Sessions。

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

  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中获取原始设备值,结合用户点击的设备ID保存到session中,供下次请求使用。

我更新你的代码如下:

// ...
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)
// ...

希望这对您有所帮助。

关于session - 如何使用 String 扩展 session.Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50888875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com