duan0065626385 2013-09-12 13:42
浏览 43
已采纳

调用ExecuteTemplate会收到I / O超时错误

I have a function that makes a call to an external API using a Go http.Client, parses the result, and uses the result in the template executed afterwards. Occasionally, the external API will respond slowly (~20s), and the template execution will fail citing "i/o timeout", or more specifically,

template: :1:0: executing "page.html" at <" \t\t\t\t\t\t\t\t\...>: write tcp 127.0.0.1:35107: i/o timeout

This always coincides with a slow API response, but there is always a valid response in the JSON object, so the http.Client is receiving a proper response. I am just wondering if anyone could point me towards what could be causing the i/o timeout in the ExecuteTemplate call.

I have tried ResponseHeaderTimeout and DisableKeepAlives in the client transport (both with and without those options) to no avail. I've also tried setting the request's auto-close value to true to no avail. A stripped-down version of the template generation code is below:

func viewPage(w http.ResponseWriter, r *http.Request) {

    tmpl := pageTemplate{}

    duration, _ := time.ParseDuration("120s")
    tr := &http.Transport{
        ResponseHeaderTimeout: duration,
        DisableKeepAlives:     true,
    }
    client := &http.Client{Transport: tr}

    req, _ := http.NewRequest("GET", "http://example.com/some_function", nil)
    req.Close = true
    resp, _ := client.Do(req)
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)

    var res api_response // some struct that matches the JSON response
    err = json.Unmarshal(body, &res)

    t, _ := template.New("page.html")
    err = t.ExecuteTemplate(w, "page.html", tmpl)
}
  • 写回答

1条回答 默认 最新

  • dse3168 2013-09-12 14:45
    关注

    The timeout on this line:

    err = t.ExecuteTemplate(w, "page.html", tmpl)
    

    means that the outgoing response is timing out when being written into, so nothing you change in the locally created client should affect it. It also does make sense that a slow response from that client increases the chance of the timeout on w, since the deadline is set when the response is created, before your handler is called, so a slow activity from your handler will increase the chances of a timeout.

    There's no write timeout on the http.Server instance used by http.ListenAndServe, so you must be setting the Server.WriteTimeout field explicitly on the created server.

    As a side note, there are errors being ignored in that handler, which is a strongly discouraged practice.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。