登录
首页 >  Golang >  Go问答

JSON格式的 cookie 无法被解析

来源:stackoverflow

时间:2024-03-24 12:18:45 467浏览 收藏

在 Go 中,读取 JSON 格式的 cookie 存在问题。HTTP cookie 值中不允许使用双引号、逗号和空格等字符,而 JSON 广泛使用这些字符。为了解决此问题,建议在设置 cookie 时对其进行 Base64 编码,并在读取 cookie 时对其进行 Base64 解码,从而将 JSON 数据安全地传输。

问题内容

我有一个情况,我想在 go 中读取 cookie 的内容。但是 cookie 的内容是 json 格式。 (无法更改 cookie 的格式)

例如 cookie 的内容可能是:

{"id":"abc","data":"information","on_off":false}

在 javascript 中,我可以轻松读取 cookie 的内容并解析它。

另一方面,使用 go,当我尝试使用 r.cookie('my_cookie') 读取 cookie 时,出现以下错误:http:命名的 cookie 不存在

如果我将 cookie 修改为简单的字符串,那么它会按预期工作。

有谁知道这种情况该怎么办吗?在 go 中是否无法读取这样的 cookie?

当我使用 r.header.get["cookie"] 时,它返回的输出确实包含 cookie 及其 json 值(在所有其他 cookie 中列出)


解决方案


JSON 使用许多 characters not permitted in HTTP cookie values per the RFC - 例如,不允许使用双引号、逗号和空格字符。通过 cookie 传输 JSON 数据的最简单方法可能是在设置 cookie 时对其进行 Base64 编码,并在读取 cookie 时对其进行 Base64 解码,使用 encoding/base64 包。

以上就是《JSON格式的 cookie 无法被解析》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>