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

How to assign BSON _Id to a cookie (Go, Mongodb)

我正在尝试创建一个 go cookie。我想从 Mongodb 分配 Id 以存储在 Cookie 中。但是在编译时出现如下错误:-

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

以下是我的代码:-

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
}

提前致谢。

这里是这个问题的解决方案。

Cookie 结构如下:

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

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

曲奇电话

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

更多详情Click Here。这个 link 对我帮助很大。希望有人会发现这个答案有用。