dqdjfb2325 2016-01-29 10:50
浏览 27
已采纳

如何将BSON _Id分配给cookie(Go,Mongodb)

I was trying to create a go cookie. I want to assign Id from Mongodb to be stored in the Cookie. But while compiling I am getting an error as follows:-

"unknown http.Cookie field 'Id' in struct literal"

The following is my code:-

getUser := user.CheckDB()
expiration := time.Now().Add(365 * 24 * time.Hour)

//The Error is Caused by the Next Line
cookie := http.Cookie{Id: getUser[0].Id, Name: getUser[0].Email, Value: getUser[0].Password, Expires: expiration}
http.SetCookie(w, &cookie)



func (this *User) CheckDB() []User {
    var results []User
    sess, db := GetDatabase()
    defer sess.Close()
    c := db.C("user")
    uname := &this.Email
    err := c.Find(bson.M{"email": *uname}).Sort("-id").All(&results)
    if err != nil {
        panic(err)
    } else {
        fmt.Println("Results All: ", results)
        return results
    }
}

type Cookie struct {
    Id         bson.ObjectId `bson:"_id,omitempty"`
    Name       string
    Value      string
    Path       string
    Domain     string
    Expires    time.Time
    RawExpires string
    MaxAge     int
    Secure     bool
    HttpOnly   bool
    Raw        string
    Unparsed   []string
}

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dongxinpa3101 2016-02-08 06:09
    关注

    Here is a solution for this problem.

    Cookie struct below:

    type Cookie struct {    
        Name       string
        Value      string
        Path       string
        Domain     string
        Expires    time.Time
        RawExpires string
        MaxAge   int
        Secure   bool
        HttpOnly bool
        Raw      string
        Unparsed []string
    }
    

    Cookie Creation

     value := map[string]string{
            "id": cookieId,
        }
        if encoded, err := ckieHandler.Encode("session", value); err == nil {
            cookie := &http.Cookie{
            Name:  "session",
            Value: encoded,
            Path:  "/",
            }
            http.SetCookie(response, cookie)
        }
    

    Cookie Call

    if cookie, err := request.Cookie("session"); err == nil {
            cookieValue := make(map[string]string)
            if err = ckieHandler.Decode("session", cookie.Value, &cookieValue); err == nil {
                id = cookieValue["id"] // **Pass BSON ID here**
            }
        }
    

    For more details Click Here. This link helped me a lot. Hoping someone will find this answer useful.

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

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探