douqilai4263 2019-03-17 18:10
浏览 364
已采纳

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

I was using http.NewRequest to make a GET Request.

I deliberately tried to tamper the API url just to check if my err handling works.

But its not working as expected . In err value is returned and I am unable to compare it.

    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))
        }

The output is as below:

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

But I am expecting to print "Wrong".

  • 写回答

2条回答 默认 最新

  • duanlu7223 2019-03-17 18:15
    关注

    The HTTP call succeeds (the call went through to the server, and response came back), that's why err is nil. It's just that the HTTP status code is not http.StatusOK (but by judging the response document, it's http.StatusNotFound).

    You should check the HTTP status code like this:

    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.
    

    Also note that certain API endpoints might return other than http.StatusOK for success, such as HTTP 201 - Created, or HTTP 202 - Accepted etc. If you want to check all success status codes, you can do it like this:

    // 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条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办