我想制作一个 hello world Web 应用程序,能够正确捕获模板错误。所以我需要缓冲响应但不知道该怎么做。我已经整理了这段代码。这是在 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()))
}
Run Code Online (Sandbox Code Playgroud)
bytes.Buffer有一个Bytes方法,因此您实际上不需要调用String并将其转换为[]byte:
w.Write(buf.Bytes())
Run Code Online (Sandbox Code Playgroud)
此外,将错误写入 stderr 是一个很好的做法。只需将您的替换fmt为log:
if err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
Run Code Online (Sandbox Code Playgroud)