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

    点赞 评论 复制链接分享

相关推荐