在 Go 中使用 http.NewRequest 处理错误

Bal*_*ran 6 http go

我正在使用http.NewRequestGET 请求。

我故意试图篡改 API url 只是为了检查我的错误处理是否有效。

但它没有按预期工作。在 err 值被返回,我无法比较它。

    jsonData := map[string]string{"firstname": "Nic", "lastname": "Raboy"}
    jsonValue, _ := json.Marshal(jsonData)    
request, err := http.NewRequest("POST", "http://httpbin.org/postsdf", bytes.NewBuffer(jsonValue))


        request.Header.Set("Content-Type", "application/json")
        client := &http.Client{}
        response, err := client.Do(request)

        if err != nil {
            fmt.Println("wrong")

        } else {
            data, _ := ioutil.ReadAll(response.Body)
            fmt.Println(string(data))
        }
Run Code Online (Sandbox Code Playgroud)

输出如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server.  If you entered the URL manually please check your spelling and try again.</p>
Run Code Online (Sandbox Code Playgroud)

但我期待打印“错误”。

icz*_*cza 15

该HTTP调用成功(呼叫经历了服务器,并响应回来),这就是为什么errnil。只是HTTP状态码不是http.StatusOK(而是通过响应文档判断,是http.StatusNotFound)。

您应该像这样检查 HTTP 状态代码:

response, err := client.Do(request)
if err != nil {
    fmt.Println("HTTP call failed:", err)
    return
}
// Don't forget, you're expected to close response body even if you don't want to read it.
defer response.Body.Close()

if response.StatusCode != http.StatusOK {
    fmt.Println("Non-OK HTTP status:", response.StatusCode)
    // You may read / inspect response body
    return
}

// All is OK, server reported success.
Run Code Online (Sandbox Code Playgroud)

另请注意,某些 API 端点可能会返回非http.StatusOK成功,例如HTTP 201 - Created,HTTP 202 - Accepted等。 如果您想检查所有成功状态代码,您可以这样做:

// Success is indicated with 2xx status codes:
statusOK := response.StatusCode >= 200 && response.StatusCode < 300
if !statusOK {
    fmt.Println("Non-OK HTTP status:", response.StatusCode)
    // You may read / inspect response body
    return
}
Run Code Online (Sandbox Code Playgroud)