How to buffer a response in web app in golang?

huangapple go评论156阅读模式
英文:

How to buffer a response in web app in golang?

问题

我想制作一个能够正确捕获模板错误的 "Hello World" 网页应用程序。所以我需要缓冲响应,但不知道如何做。我已经组合了以下代码。这是在 Go 语言中缓冲响应的方式吗?

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()))
}
英文:

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()))
}

答案1

得分: 5

bytes.Buffer有一个Bytes方法,所以你实际上不需要调用String并将其转换为[]byte

w.Write(buf.Bytes())

此外,将错误写入stderr是一个好的实践。只需将你的fmt替换为log

if err != nil {
    log.Println(err)
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}
英文:

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

得分: 2

bytes.Buffer有一个内置的方法可以将内容写入到io.Writer中:

func get_handler(w http.ResponseWriter, r *http.Request) {
    buf := new(bytes.Buffer)

    //填充缓冲区

    _, err := buf.WriteTo(w)
    if err != nil {
        log.Println(err)
    }
}

文档:http://golang.org/pkg/bytes/#Buffer.WriteTo

英文:

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

答案3

得分: 2

你可以通过向bytes.Buffer写入内容来直接使用它,但这样做会导致每次请求都丢弃缓冲区。

使用池化的方法(安全地在使用之间重置内容,但保留缓冲区)可能会有一些收益:

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)
}

这里使用了bpool库。

英文:

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.

huangapple
  • 本文由 发表于 2015年9月14日 23:41:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/32568746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定