首页 > 解决方案 > 对错误 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

我的要求:我希望正确处理这个错误,但我不确定如何,所以我的应用程序可以优雅地结束。

标签: httpgo

解决方案


处理 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

推荐阅读