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

如何在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()))
}

图片转代码服务由CSDN问答提供 功能建议

我想制作一个可以正确捕获模板错误的Hello World Web应用程序。 所以我需要缓冲响应,但不知道该怎么做。 我把这段代码放在一起了。 这是在golang中缓冲响应的方法吗?

  func get_handler(w http.ResponseWriter,r * http.Request){
 
 buf:= new(bytes.Buffer)
 err:= templates.ExecuteTemplate  (buf,“ hello.html”,nil)
,如果err!= nil {
 fmt.Println(err.Error())
 http.Error(w,err.Error(),http.StatusInternalServerError)\  n 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
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dqmg80654 2015-09-14 16:05

    bytes.Buffer has a built-in method for writing out to an io.Writer:

    func get_handler(w http.ResponseWriter, r *http.Request) {
        buf := new(bytes.Buffer)
    
        //fill buffer
    
        _,err := buf.WriteTo(w)
        if err != nil { 
             log.Println(err)
        }
    }
    

    docs: http://golang.org/pkg/bytes/#Buffer.WriteTo

    评论
    解决 无用
    打赏 举报
  • donglin9717 2015-09-14 23:08

    You can use a bytes.Buffer "as is" by writing into it, but at the cost of discarding the buffer on every request.

    Using a pooled approach (that safely resets the contents between use, but retains the buffer) can have some gains:

    var bufPool *bpool.BufferPool
    
    func YourHandler(w http.ResponseWriter, r *http.Request) {
        buf := bufPool.Get()
        defer bufPool.Put(buf)
        err := template.ExecuteTemplate(buf, "forms/create.html", user)
        // or err := json.NewEncoder(buf).Encode(value)
        if err != nil {
          return err
        }
    
        buf.WriteTo(w)
    }
    

    This uses the bpool library.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题