去:恐慌:运行时错误:无效的内存地址或零指针取消引用
来源:Golang技术栈
2023-03-09 20:02:50
0浏览
收藏
Golang不知道大家是否熟悉?今天我将给大家介绍《去:恐慌:运行时错误:无效的内存地址或零指针取消引用》,这篇文章主要会讲到golang等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!
问题内容
运行我的 Go 程序时,它会发生恐慌并返回以下内容:
panic: runtime error: invalid memory address or nil pointer dereference [signal 0xb code=0x1 addr=0x38 pc=0x26df] goroutine 1 [running]: main.getBody(0x1cdcd4, 0xf800000004, 0x1f2b44, 0x23, 0xf84005c800, ...) /Users/matt/Dropbox/code/go/scripts/cron/fido.go:65 +0x2bb main.getToken(0xf84005c7e0, 0x10) /Users/matt/Dropbox/code/go/scripts/cron/fido.go:140 +0x156 main.main() /Users/matt/Dropbox/code/go/scripts/cron/fido.go:178 +0x61 goroutine 2 [syscall]: created by runtime.main /usr/local/Cellar/go/1.0.3/src/pkg/runtime/proc.c:221 goroutine 3 [syscall]: syscall.Syscall6() /usr/local/Cellar/go/1.0.3/src/pkg/syscall/asm_darwin_amd64.s:38 +0x5 syscall.kevent(0x6, 0x0, 0x0, 0xf840085188, 0xa, ...) /usr/local/Cellar/go/1.0.3/src/pkg/syscall/zsyscall_darwin_amd64.go:199 +0x88 syscall.Kevent(0xf800000006, 0x0, 0x0, 0xf840085188, 0xa0000000a, ...) /usr/local/Cellar/go/1.0.3/src/pkg/syscall/syscall_bsd.go:546 +0xa4 net.(*pollster).WaitFD(0xf840085180, 0xf840059040, 0x0, 0x0, 0x0, ...) /usr/local/Cellar/go/1.0.3/src/pkg/net/fd_darwin.go:96 +0x185 net.(*pollServer).Run(0xf840059040, 0x0) /usr/local/Cellar/go/1.0.3/src/pkg/net/fd.go:236 +0xe4 created by net.newPollServer /usr/local/Cellar/go/1.0.3/src/pkg/net/newpollserver.go:35 +0x382
我查看了其他人对相同异常的响应,但看不到任何简单的东西(即未处理的错误)。
我在一台无法访问代码中列出的 API 服务器的机器上运行它,但我希望它会返回一个适当的错误(因为我试图捕捉这种错误)。
package main /* Fido fetches the list of public images from the Glance server, captures the IDs of images with 'status': 'active' and then queues the images for pre-fetching with the Glance CLI utility `glance-cache-manage`. Once the images are added to the queue, `glance-cache-prefetcher` is called to actively fetch the queued images into the local compute nodes' image cache. See http://docs.openstack.org/developer/glance/cache.html for further details on the Glance image cache. */ import ( "bytes" "encoding/json" "fmt" "io/ioutil" /* "log" "log/syslog" */ "net/http" "os" "os/exec" ) func prefetchImages() error { cmd := exec.Command("glance-cache-prefetcher") err := cmd.Run() if err != nil { return fmt.Errorf("glance-cache-prefetcher failed to execute properly: %v", err) } return nil } func queueImages(hostname string, imageList []string) error { for _, image := range imageList { cmd := exec.Command("glance-cache-manage", "--host=", hostname, "queue-image", image) err := cmd.Run() if err != nil { return fmt.Errorf("glance-cache-manage failed to execute properly: %v", err) } else { fmt.Printf("Image %s queued", image) } } return nil } func getBody(method string, url string, headers map[string]string, body []byte) ([]byte, error) { client := &http.Client{} req, err := http.NewRequest(method, url, bytes.NewReader(body)) if err != nil { return nil, err } for key, value := range headers { req.Header.Add(key, value) } res, err := client.Do(req) defer res.Body.Close() if err != nil { return nil, err } var bodyBytes []byte if res.StatusCode == 200 { bodyBytes, err = ioutil.ReadAll(res.Body) } else if err != nil { return nil, err } else { return nil, fmt.Errorf("The remote end did not return a HTTP 200 (OK) response.") } return bodyBytes, nil } func getImages(authToken string) ([]string, error) { type GlanceDetailResponse struct { Images []struct { Name string `json:"name"` Status string `json:"status"` ID string `json:"id"` } } method := "GET" url := "http://192.168.1.2:9292/v1.1/images/detail" headers := map[string]string{"X-Auth-Token": authToken} bodyBytes, err := getBody(method, url, headers, nil) if err != nil { return nil, fmt.Errorf("unable to retrieve the response body from the Glance API server: %v", err) } var glance GlanceDetailResponse err = json.Unmarshal(bodyBytes, &glance) if err != nil { return nil, fmt.Errorf("unable to parse the JSON response:", err) } imageList := make([]string, 10) for _, image := range glance.Images { if image.Status == "active" { imageList = append(imageList, image.ID) } } return imageList, nil } func getToken() (string, error) { type TokenResponse struct { Auth []struct { Token struct { Expires string `json:"expires"` ID string `json:"id"` } } } method := "POST" url := "http://192.168.1.2:5000/v2.0/tokens" headers := map[string]string{"Content-type": "application/json"} creds := []byte(`{"auth":{"passwordCredentials":{"username": "glance", "password":""}, "tenantId":" "}}`) bodyBytes, err := getBody(method, url, headers, creds) if err != nil { return "", err } var keystone TokenResponse err = json.Unmarshal(bodyBytes, &keystone) if err != nil { return "", err } authToken := string((keystone.Auth[0].Token.ID)) return authToken, nil } func main() { /* slog, err := syslog.New(syslog.LOG_ERR, "[fido]") if err != nil { log.Fatalf("unable to connect to syslog: %v", err) os.Exit(1) } else { defer slog.Close() } */ hostname, err := os.Hostname() if err != nil { // slog.Err("Hostname not captured") os.Exit(1) } authToken, err := getToken() if err != nil { // slog.Err("The authentication token from the Glance API server was not retrieved") os.Exit(1) } imageList, err := getImages(authToken) err = queueImages(hostname, imageList) if err != nil { // slog.Err("Could not queue the images for pre-fetching") os.Exit(1) } err = prefetchImages() if err != nil { // slog.Err("Could not queue the images for pre-fetching") os.Exit(1) } return }
正确答案
根据文档func (*Client) Do
:
“如果由客户端策略(例如 CheckRedirect)引起,或者存在 HTTP 协议错误,则会返回错误。非 2xx 响应不会导致错误。
当 err 为 nil 时,resp 总是包含一个非 nil 的 resp.Body。”
然后看这段代码:
res, err := client.Do(req) defer res.Body.Close() if err != nil { return nil, err }
我猜那err
不是nil
。在检查. .Close()
_res.Body``err
唯一的defer
延迟函数调用。立即访问字段和方法。
因此,请尝试立即检查错误。
res, err := client.Do(req) if err != nil { return nil, err } defer res.Body.Close()
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
版本声明
本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除

- 上一篇
- 如何在 Go 结构中设置默认值

- 下一篇
- 为什么在同一个 goroutine 中使用无缓冲通道会导致死锁?
评论列表
-
- 心灵美的苗条
- 这篇博文太及时了,太细致了,很棒,已收藏,关注作者大大了!希望作者大大能多写Golang相关的文章。
- 2023-03-17 22:56:20
-
- 甜美的老师
- 这篇文章内容出现的刚刚好,师傅加油!
- 2023-03-16 20:56:48
-
- 坚定的美女
- 很好,一直没懂这个问题,但其实工作中常常有遇到...不过今天到这,看完之后很有帮助,总算是懂了,感谢作者分享技术文章!
- 2023-03-14 04:36:46
-
- 谨慎的红牛
- 太全面了,已加入收藏夹了,感谢作者大大的这篇文章,我会继续支持!
- 2023-03-10 16:45:30
查看更多
最新文章
-
- 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 Make Song
- AI Make Song是一款革命性的AI音乐生成平台,提供文本和歌词转音乐的双模式输入,支持多语言及商业友好版权体系。无论你是音乐爱好者、内容创作者还是广告从业者,都能在这里实现“用文字创造音乐”的梦想。平台已生成超百万首原创音乐,覆盖全球20个国家,用户满意度高达95%。
- 26次使用
-
- SongGenerator
- 探索SongGenerator.io,零门槛、全免费的AI音乐生成器。无需注册,通过简单文本输入即可生成多风格音乐,适用于内容创作者、音乐爱好者和教育工作者。日均生成量超10万次,全球50国家用户信赖。
- 21次使用
-
- BeArt AI换脸
- 探索BeArt AI换脸工具,免费在线使用,无需下载软件,即可对照片、视频和GIF进行高质量换脸。体验快速、流畅、无水印的换脸效果,适用于娱乐创作、影视制作、广告营销等多种场景。
- 23次使用
-
- 协启动
- SEO摘要协启动(XieQiDong Chatbot)是由深圳协启动传媒有限公司运营的AI智能服务平台,提供多模型支持的对话服务、文档处理和图像生成工具,旨在提升用户内容创作与信息处理效率。平台支持订阅制付费,适合个人及企业用户,满足日常聊天、文案生成、学习辅助等需求。
- 23次使用
-
- Brev AI
- 探索Brev AI,一个无需注册即可免费使用的AI音乐创作平台,提供多功能工具如音乐生成、去人声、歌词创作等,适用于内容创作、商业配乐和个人创作,满足您的音乐需求。
- 25次使用
查看更多
相关文章
-
- 老师代码没有自动跟踪?
- 2023-03-07 439浏览
-
- c程序fork并等待golang进程状态
- 2023-03-05 262浏览
-
- GOLANG使用Context管理关联goroutine的方法
- 2022-12-28 193浏览
-
- 怎么用Golang将MySQL表转储为JSON
- 2023-03-07 188浏览
-
- Golang 检查字符串是否为有效路径?
- 2023-03-10 500浏览