英文:
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)
}
}
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论