drb88830 2018-06-05 07:34
浏览 104

使用golang终止IP层的http请求

I am making an http post request to a server using golang. Suppose the server is currently turned off (Means the machine on which the server runs is turned off) then the request is stuck at the IP layer. So my program execution is unable to proceed further. It is unable to proceed to the Application layer. So is there any way in golang to stop this. I am using the following code.

req, err := http.NewRequest("POST", url, bytes.NewReader(b))
       if err != nil {
               return errors.Wrap(err, "new request error")
       }
resp, err := http.DefaultClient.Do(req)
       if err != nil {
               return errors.Wrap(err, "http request error")
       }
       defer resp.Body.Close()

Is there anything that can be added to this, to terminate the request if it doesn't find anything from the IP layer.

  • 写回答

3条回答 默认 最新

  • douting1871 2018-06-05 08:08
    关注

    The default http Client has no timeout. You can create an explicit http.Client yourself and set the timeout:

    var cl = &http.Client{
        Timeout: time.Second * 10,
    }
    
    resp, err := cl.Do(req)
    
    if err != nil {
        // err will be set on timeout
        return errors.Wrap(err, "http request error")
    }
    defer resp.Body.Close()
    

    If the server does not answer any more in the middle of a request, you can handle the timeout.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度