gpt4 book ai didi

Go 程序在连接被拒绝后退出

转载 作者:数据小太阳 更新时间:2023-10-29 03:45:44 26 4
gpt4 key购买 nike

我正在向网站发送 get 请求并在循环中获取状态代码,当循环向不存在的网站发送 get 请求时,它会中断程序。

go版本go1.12.6 darwin/amd64

func getRequest(url string) int {

http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}

resp, err := http.Get(url)
if err != nil {
log.Fatalln(err)
}

defer resp.Body.Close()

return resp.StatusCode
}

func checker(info []accountinfo) {
var request string
var statusCode int

for i := range info {
request = fmt.Sprintf("https://%s/", info[i].domain)
statusCode = getRequest(request)
if statusCode == 200 {
fmt.Println("That's ok")
} else {
fmt.Println(info[i].domain, "not found or content is not valid")
}

}
}

我希望它打印“something.com not found or content is not valid”。但它抛出了下面的错误。

2019/09/05 17:19:43 Get https://something.com/: dial tcp ip:443: connect: connection refused
exit status 1

编辑

使用 Println 而不是 Fatalln 会产生另一个错误:

2019/09/05 17:52:18 Get https://something.com/: dial tcp ip:443: connect: connection refused
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x124eebf]

goroutine 1 [running]:
main.getRequest(0xc0000ae0e0, 0x1a, 0x0)
/Users/ozan/monitoring-development/v2/main.go:147 +0xff
main.checker(0xc000584000, 0x8d, 0x100)
/Users/ozan/monitoring-development/v2/main.go:110 +0xd3
main.main()
/Users/ozan/monitoring-development/v2/main.go:67 +0x4dd
exit status 2

最佳答案

log.Fatalln,顾名思义,documentation clearly states , 打印错误并退出程序。如果您不想退出,请改用 log.Println

“未找到或无效”错误的逻辑基于状态代码,但为了获得状态代码,请求必须完成。请求无法完成到不存在或拒绝连接的主机。所以你需要考虑两种类型的“失败”情况:

  1. 传输级错误,例如 DNS 故障、连接被拒绝/超时等。
  2. 协议(protocol)级错误,如 HTTP 状态 500 等。

另请注意,您状态 200 视为成功;这可能是预期的,也可能不是,因为整个 2xx 状态代码块都是成功代码(例如 204 No Content 是常见的成功响应)。

你可能想要这样的东西:

resp, err := http.Get(url)
if err != nil {
log.Println(err) // Assuming you want to see what the error actually was
return -1 // Not perfect, but at least the caller will treat it as a "non-success" status code and give your expected result
}

更好的实现是返回状态代码和错误,并在 checker 中正确处理这两者。

关于Go 程序在连接被拒绝后退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57807990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com