问题描述
我期望的是:
接收给定申请的任何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