http - 对错误 URL 的请求使我的 golang http 请求使我的主线程崩溃
问题描述
我所期望的:
接收给定申请的任何 HTTP 状态代码。
我得到了什么:
退出状态 2。
我的想法:
可能是传输层的错误?但我不知道如何治疗。
重现给定错误的代码:
package main
import (
"fmt"
"net/http"
"strings"
)
func main() {
url := "http://32.67.163.173:9200/suprin/_doc/"
requestType := "POST"
body := strings.NewReader("")
req, err := http.NewRequest(requestType, url, body)
if err != nil {
fmt.Println("Unable to create the request: " + err.Error())
}
fmt.Println("1")
req.Header.Set("Content-Type", "application/json")
fmt.Println("2")
resp, err := http.DefaultClient.Do(req)
fmt.Println("3")
if resp.StatusCode != 201 {
fmt.Println("4")
fmt.Println("httpe error: " + resp.Status)
}
fmt.Println("5")
}
我的错误:
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x10 pc=0x62c413]
goroutine 1 [running]:
main.main()
C:/Users/Luado/Desktop/Goling-in-the rain/http_req_broken_url/http_req.go:25 +0x2e3
exit status 2
我的要求:我希望正确处理这个错误,但我不确定如何,所以我的应用程序可以优雅地结束。
解决方案
处理 GO 中的每个错误。
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println(err.Error())
return
}
╰─# go run main.go 1 ↵
1
2
Post "http://32.67.163.173:9200/suprin/_doc/": dial tcp 32.67.163.173:9200: connect: connection refused
推荐阅读
- php - 如何为有回复的评论显示显示回复按钮?
- laravel - Laravel Vue - 存储数组
- java - 延迟来自队列rabbitmq spring的消息
- reactjs - 如何更快地更新 React Native 应用程序中的 ERC20 代币数量?
- python - 点云缩小
- c# - 如何从表示为字符串的访问控制列表中制作 SystemAcl 对象?
- python-3.x - 通过网络将数据并行发送到多个接收者
- ios - 使用令牌的 WKWebview 身份验证不起作用 - Swift
- html - SVG 文本标签未在组上方呈现
- php - 仅允许来自 PHP 内部的 API 请求的方法