我正在尝试创建一个 go cookie。我想从 Mongodb 分配 Id 以存储在 Cookie 中。但是在编译时出现如下错误:-
“结构文字中的未知 http.Cookie 字段‘Id’”
以下是我的代码:-
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 .这个链接对我帮助很大。希望有人会发现这个答案有用。
关于mongodb - 如何将 BSON _Id 分配给 cookie(Go,Mongodb),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35082618/