Probably a simple question, but I am having issues delaying the output in a request handler function. I'm using "bufio" to write to when I execute my templates instead of the response writer, but it seems like the buffer can only hold so much before it spits things out. I'm concerned that it will spit out part of the page, then encounter an error, leaving an incomplete and unintelligible response. What is the best strategy for ensuring that everything stays buffered until it's ready to be released into the wild?
If you want to completely buffer the output use bytes.Buffer
instead, example:
var bufferPool = &sync.Pool{
New: func() interface{} {
return &bytes.Buffer{}
},
}
func getBuffer() (buf *bytes.Buffer) {
return bufferPool.Get().(*bytes.Buffer)
}
func putBuffer(buf *bytes.Buffer) {
buf.Reset()
bufferPool.Put(buf)
}
func handler(w http.ResponseWriter, req *http.Request) {
buf := getBuffer()
defer putBuffer(buf)
//....
fmt.Fprintf(buf, .....)
buf.WriteTo(w)
}
You could just use a bytes.Buffer
func Handler(w http.ResponseWriter, req *http.Request) {
tmp, err := template.New("hello").Parse("Hello {{.World}}")
if err != nil {
http.Error(w, "Error", 500)
return
}
buf := &bytes.Buffer{}
if err := tmp.Execute(buf, map[string]string{"World": "World"}); err != nil {
http.Error(w, "Error", 500)
return
}
w.Write(buf.Bytes())
}