在使用gorilla/sessions时遇到了个问题

Jasonnnnnnnn · 2017-10-08 02:11:10 · 1520 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2017-10-08 02:11:10 的主题,其中的信息可能已经有所发展或是发生改变。

1.png

我定义了一个结构体user,有id,username,password属性,我想把从数据库拿出来的user整个保存到session里面,以user的id作为key,现在我看到了session里面倒是有个map,是我取session的时候有问题吗?还是说我保存的时候有问题?


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1520 次点击  
加入收藏 微博
12 回复  |  直到 2017-10-08 08:56:22
channel
channel · #1 · 7年之前

使用感觉没问题,唯一一点,你这里的 store 怎么获取的?要保证它全局唯一

Jasonnnnnnnn
Jasonnnnnnnn · #2 · 7年之前

@channel 我是直接在handle外面写 var store = sessions.NewCookieStore([]byte("session_cookie"))

channel
channel · #3 · 7年之前

那你在 session.Save 之后,紧接着取里面的值,看看能否取到

Jasonnnnnnnn
Jasonnnnnnnn · #4 · 7年之前

@channel 取到的是 {0 }

channel
channel · #5 · 7年之前

那这还不能说明问题吗?你看看 u 本身是不是就是 {0 } 啊!

Jasonnnnnnnn
Jasonnnnnnnn · #6 · 7年之前
channelchannel #5 回复

那这还不能说明问题吗?你看看 `u` 本身是不是就是 {0 } 啊!

不是呀 里面有值的 分别对应id username password

channel
channel · #7 · 7年之前

你确定输出 u 中的 id、username 和 password 有值?

Jasonnnnnnnn
Jasonnnnnnnn · #8 · 7年之前
channelchannel #7 回复

你确定输出 u 中的 id、username 和 password 有值?

2.png

嗯嗯 现在变成了session.Save 之后能取出来,在外面取不出来了

channel
channel · #9 · 7年之前

那说明现在 session 使用没有问题了。看对应的 cookie 中有没有 "users" 的值。

Jasonnnnnnnn
Jasonnnnnnnn · #10 · 7年之前
channelchannel #9 回复

那说明现在 session 使用没有问题了。看对应的 cookie 中有没有 "users" 的值。

没有额,一直都是报 the value is not valid ,但是如果不存user而只是存个id,这样第二次就不会报错

channel
channel · #11 · 7年之前

你提醒了我。你直接存一个结构,该结构需要实现 sessions 中的 Codec 接口,进行序列化:

// Codec defines an interface to encode and decode cookie values.
type Codec interface {
    Encode(name string, value interface{}) (string, error)
    Decode(name, value string, dst interface{}) error
}

因为你没有实现,所以报这个错:

ErrMacInvalid = cookieError{typ: decodeError, msg: "the value is not valid"}

实际中,也不应该存整个 user,密码都存入 cookie,不合适吧。只需要存 id 或 username 就可以了!

Jasonnnnnnnn
Jasonnnnnnnn · #12 · 7年之前
channelchannel #11 回复

你提醒了我。你直接存一个结构,该结构需要实现 sessions 中的 Codec 接口,进行序列化: ```go // Codec defines an interface to encode and decode cookie values. type Codec interface { Encode(name string, value interface{}) (string, error) Decode(name, value string, dst interface{}) error } ``` 因为你没有实现,所以报这个错: `ErrMacInvalid = cookieError{typ: decodeError, msg: "the value is not valid"}` 实际中,也不应该存整个 user,密码都存入 cookie,不合适吧。只需要存 id 或 username 就可以了!

噢噢 我去实现试试

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传