JSON解码器的重复调用是由于响应结构微小变化引起的
来源:stackoverflow
2024-02-13 17:51:26
0浏览
收藏
在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《JSON解码器的重复调用是由于响应结构微小变化引起的》,聊聊,希望可以帮助到正在努力赚钱的你。
问题内容
我已将 github 和 google 身份验证系统添加到我的 web 应用程序中。我希望在这两种情况下都能获得用户电子邮件。我尝试创建一个函数来发出 api 请求并获取电子邮件。
当 google 返回 json 对象 和 github 返回 json 数组 作为响应时,我遇到了问题。
我想不出如何避免调用 json 解码器两次的方法,因为我不能为它们提供相同的类型变量。
// Sends a request to the API and // authorizes it by setting HTTP header "Authorization" to authHeader value func getUserEmail(endpoint, authHeader, provider string) (string, error) { var email string // Store user email here var client http.Client // Create client so we can modify request headers // Create a GET request to the endpoint req, err := http.NewRequest("GET", endpoint, nil) if err != nil { return "", err } // Authorize the request by using the HTTP header req.Header.Add("Authorization", authHeader) // Give the data back as JSON req.Header.Add("accept", "application/json") // Send the request resp, err := client.Do(req) if err != nil { fmt.Println("Internet connection or client policy error") return "", err } defer resp.Body.Close() if provider == "google" { var response map[string]interface{} err = json.NewDecoder(resp.Body).Decode(&response) if err != nil { fmt.Println("Error occured during decoding access token response") return "", err } email = response["email"].(string) } else if provider == "github" { var response []map[string]interface{} err = json.NewDecoder(resp.Body).Decode(&response) if err != nil { fmt.Println("Error occured during decoding access token response") return "", err } email = response[0]["email"].(string) } else { return "", errors.New("invalid provider") } return email, nil }
正确答案
您可以解组到 var 响应接口{}
。解组 json 后,您可以在 response
上执行 type 断言
来检查它是否是 []interface{}
或 map[string]interface{}
并从那里开始。
var email string var response interface{} if err := json.newdecoder(r.body).decode(&response); err != nil { return err } // if you are sure that the structure of the content of the response, // given its type, is always what you expect it to be, you can use a // quick-and-dirty type switch/assertion. switch v := response.(type) { case []interface{}: email = v[0].(map[string]interface{})["email"].(string) case map[string]interface{}: email = v["email"].(string) } // but! if you're not sure, if the apis don't provide a guarantee, // then you should guard against panics using the comma-ok idiom // at every step. if s, ok := response.([]interface{}); ok && len(s) > 0 { if m, ok := s[0].(map[string]interface{}); ok && len(m) > 0 { email, _ = m["email"].(string) } } else if m, ok := response.(map[string]interface{}); ok && len(m) > 0 { email, _ = m["email"].(string) }
您还可以根据提供程序值预先分配一个指向预期类型的指针,并将请求正文解组到其中,这将减少所需的类型断言数量,但需要指针取消引用.
var email string var response interface{} if provider == "google" { response = new(map[string]interface{}) } else if provider == "github" { response = new([]map[string]interface{}) } if err := json.NewDecoder(r.Body).Decode(response); err != nil { return err } switch v := response.(type) { case *[]map[string]interface{}: email = (*v)[0]["email"].(string) // no need to assert the slice element's type case *map[string]interface{}: email = (*v)["email"].(string) }
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《JSON解码器的重复调用是由于响应结构微小变化引起的》文章吧,也可关注golang学习网公众号了解相关技术文章。
版本声明
本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除

- 上一篇
- Golang:完全掌握 fmt.Fscanf() 和 fmt.Sscanf() 的使用方法

- 下一篇
- nats 限制队列中仍有消息,在 Go 中发送 ack 和 term
查看更多
最新文章
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
查看更多
AI推荐
-
- 笔灵AI生成答辩PPT
- 探索笔灵AI生成答辩PPT的强大功能,快速制作高质量答辩PPT。精准内容提取、多样模板匹配、数据可视化、配套自述稿生成,让您的学术和职场展示更加专业与高效。
- 24次使用
-
- 知网AIGC检测服务系统
- 知网AIGC检测服务系统,专注于检测学术文本中的疑似AI生成内容。依托知网海量高质量文献资源,结合先进的“知识增强AIGC检测技术”,系统能够从语言模式和语义逻辑两方面精准识别AI生成内容,适用于学术研究、教育和企业领域,确保文本的真实性和原创性。
- 41次使用
-
- AIGC检测-Aibiye
- AIbiye官网推出的AIGC检测服务,专注于检测ChatGPT、Gemini、Claude等AIGC工具生成的文本,帮助用户确保论文的原创性和学术规范。支持txt和doc(x)格式,检测范围为论文正文,提供高准确性和便捷的用户体验。
- 38次使用
-
- 易笔AI论文
- 易笔AI论文平台提供自动写作、格式校对、查重检测等功能,支持多种学术领域的论文生成。价格优惠,界面友好,操作简便,适用于学术研究者、学生及论文辅导机构。
- 50次使用
-
- 笔启AI论文写作平台
- 笔启AI论文写作平台提供多类型论文生成服务,支持多语言写作,满足学术研究者、学生和职场人士的需求。平台采用AI 4.0版本,确保论文质量和原创性,并提供查重保障和隐私保护。
- 41次使用
查看更多
相关文章
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览