Skip to content

Instantly share code, notes, and snippets.

@brianfoshee
Created March 28, 2016 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianfoshee/37dc836f77144b6a61de to your computer and use it in GitHub Desktop.
Save brianfoshee/37dc836f77144b6a61de to your computer and use it in GitHub Desktop.
// bufPool is a pool of byte buffers meant to used when encoding JSON responses
// out to a client.
// giving this a try over:
// https://github.com/oxtoacart/bpool/blob/master/bufferpool.go
var bufPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
// writeJSON pulls a byte buffer from bufPool and encodes JSON to it. If there
// is an error, that is returned. Otherwise, the bytes are written out to the
// ResponseWriter.
func writeJSON(w http.ResponseWriter, data interface{}) error {
buf, ok := bufPool.Get().(*bytes.Buffer)
if !ok {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return errors.New("could not get a buffer from bufPool")
}
defer func() {
// throw away any buffers that are too large. Tweak this number based
// off some median or 95th perc response size number once in real use.
if buf.Cap() > 2048 {
fmt.Println("buffer cap is over 2048. Tossing")
return
}
buf.Reset()
bufPool.Put(buf)
}()
if err := json.NewEncoder(buf).Encode(data); err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return err
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if _, err := w.Write(buf.Bytes()); err != nil {
fmt.Println("error writing bytes", err)
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment