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

标签 mongodb cookies go bson

我正在尝试创建一个 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/

相关文章:

MongoDB排序日期字符串(mm/dd/yyyy)

javascript - 如何在 django 关闭浏览器时终止 session

unit-testing - 如何对 Angular 服务与 $cookies 的交互进行单元测试?

sql - 从 Golang API 远程访问 OVH SQL 数据库

Postgresql 参数问题 $1

Java Spring 5 Get 和 findById mongo MonoOnErrorResume

javascript - 调用方法时 meteor 进入路由

node.js - 在 Mongoose 中合并两个文档的数组

javascript - 当网站访问者手动更改 URL 时,如何根据 URL 设置 Cookie

随着请求数量的增加,Go 网络服务器性能急剧下降