dongsao8279 2018-06-16 14:41
浏览 80
已采纳

如何使用String扩展session.Value

Iam using Gorilla/Sessions.

I got a template page, where the user can choose between different devices. If he uses one of the submit buttons under each device my controller function should add the id value to my existing session value.

  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)
}
}

Example: User is visiting my Device page. He uses the submit button with id=2 SessionValue["EquipmentIDs"] should be = "2" right now. After that the User is visiting the Device Page again an uses the submit button with id=6. Now the SessionValue should be = "2,6"

I am attached to the problem all day and can not get any further If you have Questions or want to see other parts of my code feel free to ask Thanks in advance

  • 写回答

1条回答 默认 最新

  • dongzhiyong8577 2018-06-17 05:51
    关注

    I thought that you should get original equipment value from the session, combine the equipment ID that user clicks on and save into session for the next request.

    I update your code as following:

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

    Hope this help.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退