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 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,