本文将讨论在部署到生产环境之前,如何在早期阶段检测到代码中存在的 nil panic 并及时修复。
在 Go 语言中,“nil panic”指的是当程序试图对空指针进行解引用或操作时发生的运行时恐慌。nil 是一个预声明的标识符,表示指针、接口、通道、映射、切片和函数类型的零值,通常用于表示未初始化或无效状态。
使用 nilaway 探测 nil panic
这里推荐一个由 Uber[1] 编写的名为 nilaway[2] 的库,可以用来检测代码中是否存在 nil panic。先看下面的代码:
// Reddit post: https://www.reddit.com/r/golang/comments/1aw00nu/didnt_know_this_go_feature_wanna_share_it_here/
// Source: https://go.dev/play/p/rPBF66OpaR1
package main
import "fmt"
type Person struct {
Name string
}
func (p *Person) GetName() string {
if p != nil {
return p.Name
}
// Is not panicking, even if p is nil
return "<p is nil, not panicking>"
}
func (p Person) GetNameFails() string {
return "Should never get here, even if you are not accessing the 'p' variable"
}
func main() {
var p *Person = nil
fmt.Println(p.GetName()) // Success
fmt.Println(p.GetNameFails()) // Fails
}
保存这段代码并使用 nilaway 来探测一下:
# Go version
$ go version
go version go1.21.3 windows/amd64
##
# Are we able to build it? Yes, building without any errors
$ go build -o service main.go
##
# Saved the code in main.go
$ go run main.go
<p is nil, not panicking>
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x0 pc=0x3f3b1c]
goroutine 1 [running]:
main.main()
C:Userssjhmediummain.go:24 +0x5c
exit status 2
##
# Installing nilaway
$ go install go.uber.org/nilaway/cmd/nilaway@latest
go: downloading go.uber.org/nilaway v0.0.0-20240221165226-a488bd0b67b3
##
# Running against source code
$ nilaway .
C:Userssjhmediummain.go:24:14: error: Potential nil panic detected. Observed nil flow from source to dereference point:
- C:Userssjhmediummain.go:24:14: literal `nil` called `GetNameFails()` via the assignment(s):
- `nil` to `p` at C:Userssjhmediummain.go:22:6
从上面的代码可以了解到:
-
代码是可以成功构建的; -
只有在运行时进入了那段代码块时才会发生 panic; -
使用 nilaway 确实可以提前探测到 panic。
如果在进入生产环境之前就能在早期阶段检测到这些 panic ,能让我们在发布应用之后睡个好觉。
uber: https://www.uber.com/
[2]
nilaway: https://github.com/uber-go/nilaway
原文始发于微信公众号(Go Official Blog):Golang 应用发布生产后想睡个好觉?推荐提前用 nilaway 扫雷!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/271506.html