dongtan6695 2015-09-14 15:41
浏览 37
已采纳

如何在Golang的Web应用程序中缓冲响应?

I want to make a hello world web app that will properly catch template error. So I need to buffer the response but don't know how to do it. I've put together this code. Is this the way to buffer a response in golang?

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

    buf := new(bytes.Buffer)
    err := templates.ExecuteTemplate(buf, "hello.html", nil)
    if err != nil {
        fmt.Println(err.Error())
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    w.Write([]byte(buf.String()))
}
  • 写回答

3条回答 默认 最新

  • dqfkd82886 2015-09-14 15:44
    关注

    bytes.Buffer has a Bytes method, so you don't actually need to call String and convert it to []byte:

    w.Write(buf.Bytes())
    

    Additionally, it's a good practice to write errors to stderr. Just replace your fmt with log:

    if err != nil {
        log.Println(err)
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器