解决 golang 中“http:未找到命名 cookie”的问题
小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《解决 golang 中“http:未找到命名 cookie”的问题》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!
我正在为几个我认识的人构建一个小型晚餐/计划管理应用程序(使用微服务)。目的是每个人都可以登录自己的帐户,然后可以使用不记名令牌 (jwt) 向其他服务进行身份验证。
此不记名令牌存储在 cookie 中。但是,设置后我找不到这个 cookie,我尝试再次检索它。
这最终会导致错误
http: named cookie not present
为什么请求的响应正文为空? 为什么我的 get 请求没有发送任何 cookie? 我该如何解决这个问题?
我在网上搜索了一下并尝试了以下方法
net/http cookie: 看起来最简单的实现,也是我在这里展示的实现。看来这个简单的例子应该可行。
cookiejar 实现: 我尝试使用 cookiejar 实现来设置和检索来自浏览器和邮递员的 cookie,但是它导致了相同的结果。我使用的 cookiejar 实现在 https://golang.org/pkg/net/http/cookiejar/?m=all#new
中有描述
设置为特定 url 和额外 get 请求: 我尝试将 cookie 放置在我的域内的不同特定 url 上。在某些时候,cookie 似乎只能从某个特定的绝对 url 检索,但事实并非如此。
httputil dumprequestout: 我发现net/http的实用程序包中有一个名为dumprequestout的函数,这个函数可能能够从请求中提取主体,但它也是空的。
将 cookie“安全”标志设置为 false: 我发现一个建议,即安全标志使 cookie 无法读取。不幸的是,更改安全标志没有效果。
postman 清楚地表明 cookie 确实存在。我的浏览器(firefox)也显示cookies存在,但它们被赋予了一个相当抽象的名称。 postman 请求可以在 https://www.getpostman.com/collections/fccea5d5dc22e7107664 找到
如果我尝试使用 golang 中的“net/http”包检索 cookie,响应正文将显示为空。
在对用户/密码组合进行身份验证后,我设置会话令牌并直接重定向客户端。
// settokenandredirect sets an access token to the cookies
func settokenandredirect(w http.responsewriter, r *http.request, db *mgo.session, u *user.user, redirecturl string) *handler.apperror {
// generate a unique id for the session token.
tokenid := uuid.must(uuid.newv4()).string()
//set the expiration time (found in config.config.go)
expirationtime := time.now().add(config.expiretime)
// set the cookie with the jwt
http.setcookie(w, &http.cookie{
name: config.accesstokenname,
value: createtoken(u.userid, expirationtime, tokenid, r.header.get("user-agent")),
expires: expirationtime,
httponly: true,
secure: false,
})
// redirects user to provided redirect url
if redirecturl == "" {
return handler.apperrorf(417, nil, "no redirect url has been provided")
}
http.redirect(w, r, redirecturl, 200)
return nil
}
我尝试按如下方式验证传入请求和 jwt 令牌。
// all handlers will have this adapted servehttp function
func (fn apphandler) servehttp(w http.responsewriter, r *http.request) {
if err := authorize(w, r); err != nil {
http.error(w, fmt.sprintf("not authorized: %v", err), http.statusunauthorized)
return
}
if e := fn(w, r); e != nil { // e is *apperror, not os.error.
log.printf("handler error: status code: %d, message: %s, underlying err: %#v",
e.code, e.message, e.error)
http.error(w, e.message, e.code)
}
}
// claims defines what will be stored in a jwt access token
type claims struct {
programversion string `json:"programversion"`
useragent string `json:"useragent"`
jwt.standardclaims
}
// authorize checks if the jwt token is valid
func authorize(w http.responsewriter, r *http.request) error {
c, err := r.cookie("access_token")
if err != nil {
if err == http.errnocookie {
// the program returns this error
return err
}
return err
}
tokenstring := c.value
claim := &claims{}
tkn, err := jwt.parsewithclaims(tokenstring, claim, func(tkn *jwt.token) (interface{}, error) {
return config.jwtsigningsecret, nil
})
if !tkn.valid {
return err
}
if err != nil {
if err == jwt.errsignatureinvalid {
return err
}
return err
}
// jwt token is valid
return nil
}
设置cookie时,请求的结构如下
// pretty printed version host: localhost:8080 content-type: application/json user-agent: postmanruntime/7.11.0 cache-control: no-cache accept-encoding: gzip, deflate content-length: 68 connection: keep-alive accept: */* postman-token: 36268859-a342-4630-9fb4-c286f76d868b cookie: access_token=eyjhbgcioijiuzi1niisinr5cci6ikpxvcj9.eyjwcm9ncmftvmvyc2lvbii6ijeumc4wiiwidxnlckfnzw50ijoiug9zdg1hblj1bnrpbwuvny4xms4wiiwizxhwijoxntu2mja0mtg3lcjqdgkioijlzdlmmthhzi01ntawltq0ytetymrkzi02m2e4ywvhm2m0zdeilcjpyxqioje1ntyymdm1odcsimlzcyi6imdrlmp3dc5wcm9mawxlu2vydmljzs5hin0.bssnjtz8wokwincdz_eowybctt9t6v-7pmlxfq7gvyo
// raw version
&{post /auth/users/login?redirect=/ http/1.1 1 1 map[cache-control:[no-cache] postman-token:[d33a093e-c7ab-4eba-8c1e-914e85a0d289] cookie:[access_token=eyjhbgcioijiuzi1niisinr5cci6ikpxvcj9.eyjwcm9ncmftvmvyc2lvbii6ijeumc4wiiwidxnlckfnzw50ijoiug9zdg1hblj1bnrpbwuvny4xms4wiiwizxhwijoxntu2mja0ndu4lcjqdgkioiizotk1mmi1ns0yowqzltq4ngqtodhhnc1imdlhymi1oweynzgilcjpyxqioje1ntyymdm4ntgsimlzcyi6imdrlmp3dc5wcm9mawxlu2vydmljzs5hin0.dfa7kbet3c2q1a9n1hxgmt0qbabhgavcdbpaypbdbi8] accept-encoding:[gzip, deflate] connection:[keep-alive] content-type:[application/json] user-agent:[postmanruntime/7.11.0] accept:[*/*] content-length:[68]] 0xc0001ba140 68 [] false localhost:8080 map[redirect:[/]] map[] map[] [::1]:36584 /auth/users/login?redirect=/ 0xc00016a2a0}
获取cookie时请求的结构如下
// pretty printed version host: localhost:8080 cache-control: no-cache postman-token: 20f7584f-b59d-46d8-b50f-7040d9d40062 accept-encoding: gzip, deflate connection: keep-alive user-agent: postmanruntime/7.11.0 accept: */*
// raw version
2019/04/25 12:22:56 &{get /path/provide http/1.1 1 1 map[user-agent:[postmanruntime/7.11.0] accept:[*/*] cache-control:[no-cache] postman-token:[b79a73a3-3e08-48a4-b350-6bde4ac38d23] accept-encoding:[gzip, deflate] connection:[keep-alive]] {} 0 [] false localhost:8080 map[] map[] map[] [::1]:35884 /path/provide 0xc000138240}
设置炊具时的响应结构如下
response headers: map[location:[/] set-cookie:[access_token=eyjhbgcioijiuzi1niisinr5cci6ikpxvcj9.eyjwcm9ncmftvmvyc2lvbii6ijeumc4wiiwidxnlckfnzw50ijoir28tahr0cc1jbgllbnqvms4xiiwizxhwijoxntu2mji4odiylcjqdgkioijly2q2nwrkzi1jzjviltq4n2ytytnkyy00nmm3n2iymmuzmwuilcjpyxqioje1ntyymjgymjisimlzcyi6imdrlmp3dc5wcm9mawxlu2vydmljzs5hin0.0sovezqs2gczjwsmtvsd_u0qmv2l7m4hkf1kum08-bq; expires=thu, 25 apr 2019 21:47:02 gmt; httponly] date:[thu, 25 apr 2019 21:37:02 gmt] content-length:[0]]
我预计 authorize 函数将返回 nil。另外,如果我添加以下代码,我希望存在一些 cookie。
for _, cookie := range r.Cookies() {
fmt.Fprint(w, cookie.Name)
}
但是,authorize 函数在标题中返回错误,并且 printf 没有打印出任何 cookie。
解决方案
记住设置cookie的路径:
c := &http.Cookie{Name: name, Value: encode(value), Path: "/"}
http.SetCookie(w, c)
如果不这样做,path 将是当前请求的路径,因此 cookie 只能从这个确切的路径中获得。
理论要掌握,实操不能落!以上关于《解决 golang 中“http:未找到命名 cookie”的问题》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
自定义 Golang 结构体特定字段的 fmt 格式
- 上一篇
- 自定义 Golang 结构体特定字段的 fmt 格式
- 下一篇
- 不同查询表锁情况的方法在Oracle中
-
- Golang · Go问答 | 32分钟前 |
- Go map 用 NaN 作为键为什么难以再次删除
- 332浏览 收藏
-
- Golang · Go问答 | 1小时前 | 并发安全 · Go问答 · Go 数据竞争 map race detector
- Go 并发读写 map 为什么有时直接崩溃而不是数据竞争报告
- 218浏览 收藏
-
- Golang · Go问答 | 1小时前 |
- Go CompareAndSwap 循环为什么仍可能出现 ABA 问题
- 466浏览 收藏
-
- Golang · Go问答 | 2小时前 |
- Go 原子变量复制后为什么失去同步保证
- 217浏览 收藏
-
- Golang · Go问答 | 2小时前 |
- Go atomic.Value 为什么不能存入不同具体类型
- 268浏览 收藏
-
- Golang · Go问答 | 2小时前 |
- Go cgo 回调为什么需要先导出 Go 函数
- 175浏览 收藏
-
- Golang · Go问答 | 3小时前 |
- Go cgo 为什么不能把 Go 指针长期保存在 C 内存里
- 245浏览 收藏
-
- Golang · Go问答 | 3小时前 |
- Go cgo 交叉编译为什么提示 C compiler not found
- 463浏览 收藏
-
- Golang · Go问答 | 3小时前 |
- Go 模块代理返回 410 和 404 有什么不同
- 107浏览 收藏
-
- Golang · Go问答 | 3小时前 |
- Go vendor 目录更新后为什么依赖仍提示不一致
- 408浏览 收藏
-
- Golang · Go问答 | 4小时前 |
- Go workspace 模式为什么忽略 go.mod 里的本地 replace
- 350浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 350次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 412次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 418次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 374次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 198次使用
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go crypto/rand.Text 的长度为什么不是固定字符数
- 2026-10-04 501浏览
-
- Go strings.ToValidUTF8 清洗日志内容的边界
- 2026-10-03 501浏览
-
- Go tls.GetCertificate 为什么收不到空 ServerName 请求
- 2026-09-27 501浏览

