net / http is as follows, then fasthttp?
func doJSONWrite(w http.ResponseWriter, code int, obj interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
start := time.Now()
if err := json.NewEncoder(w).Encode(obj); err != nil {
elapsed := time.Since(start)
logrus.Errorfp("", elapsed, err.Error(), obj)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
var (
strContentType = []byte("Content-Type")
strApplicationJSON = []byte("application/json")
)
func doJSONWrite(ctx *fasthttp.RequestCtx, code int, obj interface{}) {
ctx.Response.Header.SetCanonical(strContentType, strApplicationJSON)
ctx.Response.SetStatusCode(code)
start := time.Now()
if err := json.NewEncoder(ctx).Encode(obj); err != nil {
elapsed := time.Since(start)
logrus.Errorfp("", elapsed, err.Error(), obj)
ctx.Error(err.Error(), fasthttp.StatusInternalServerError)
}
}
If you prefer to use routing framework instead, forked from fasthttp-routing with JSON support.
Most helpful comment