40 lines
881 B
Go
40 lines
881 B
Go
package api
|
|
|
|
import (
|
|
"bytes"
|
|
"net/http"
|
|
)
|
|
|
|
// Only use for bounded JSON responses, never file or runtime streams. Register
|
|
// flush before lock-release defers so a slow client cannot hold storage locks.
|
|
func deferJSONResponse(w http.ResponseWriter) (http.ResponseWriter, func()) {
|
|
b := &jsonResponseBuffer{ResponseWriter: w}
|
|
return b, func() {
|
|
if b.status != 0 {
|
|
w.WriteHeader(b.status)
|
|
}
|
|
if b.body.Len() > 0 {
|
|
_, _ = w.Write(b.body.Bytes())
|
|
}
|
|
}
|
|
}
|
|
|
|
type jsonResponseBuffer struct {
|
|
http.ResponseWriter
|
|
body bytes.Buffer
|
|
status int
|
|
}
|
|
|
|
func (w *jsonResponseBuffer) WriteHeader(status int) {
|
|
if w.status == 0 {
|
|
w.status = status
|
|
}
|
|
}
|
|
func (w *jsonResponseBuffer) Write(p []byte) (int, error) {
|
|
if w.status == 0 {
|
|
w.status = http.StatusOK
|
|
}
|
|
return w.body.Write(p)
|
|
}
|
|
func (w *jsonResponseBuffer) Unwrap() http.ResponseWriter { return w.ResponseWriter }
|