在Go

时间:2019-03-17 18:10:50

标签: http go

我当时使用http.NewRequest发出GET请求。

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

但是它没有按预期工作。在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))
        }

输出如下:

<!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>

但是我希望打印“错误”。

2 个答案:

答案 0 :(得分:4)

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.

还要注意,某些API端点可能返回http.StatusOK以外的其他字符以获取成功,例如HTTP 201 - CreatedHTTP 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
}

答案 1 :(得分:1)

您应该使用状态代码,还可以为创建的每个http请求编写一个小型处理程序。

response, err := client.Do(request)
        switch response.StatusCode {
        case 200:
            fmt.Println("work!")
            break
        case 404:
            fmt.Println("not found!")
            break
        default:
            fmt.Println("http", response.Status)
        }