Fasthttp: How to write a json return

Created on 4 Dec 2017  路  2Comments  路  Source: valyala/fasthttp

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)
    }
}

Most helpful comment

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)
    }
}

All 2 comments

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.

https://github.com/jackwhelpton/fasthttp-routing

Was this page helpful?
0 / 5 - 0 ratings

Related issues

danilobuiatti picture danilobuiatti  路  3Comments

unisqu picture unisqu  路  4Comments

bullardla picture bullardla  路  5Comments

imgurbot12 picture imgurbot12  路  5Comments

djannot picture djannot  路  3Comments