Chi: JSON response

Created on 20 Dec 2015  路  7Comments  路  Source: go-chi/chi

Now it is not very comfortable to send a JSON response:

type Foo struct {
    Bar string
}

func foo(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")

    b, err := json.Marshal(&Foo{Bar: "bar"})
    if err != nil {
        http.Error(w, err.Error(), 422)
        return
    }
    w.WriteHeader(http.StatusOK)
    w.Write(b)
}

What about add the JSON(code int, obj interface{}) method like gin or echo?

Most helpful comment

hi @hmgle I'd prefer to keep chi as just a router. If you need a responder, I suggest to use https://github.com/unrolled/render which works just fine with chi.

your code will look like:

import renderPkg "github.com/unrolled/render"

var render *render.Render

func init() {
  render = renderPkg.New() // pass options if you want
}

func x() http.Handler {
  r := chi.New()
  r.Get("/", handler)
}

func handler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  // processing..
  render.JSON(w, 200, responseObj)
}

another suggestion, is wrap the unrolled/render package by making your own "render" package that is a part of your project, and set defaults there so its setup to use across packages.

All 7 comments

hi @hmgle I'd prefer to keep chi as just a router. If you need a responder, I suggest to use https://github.com/unrolled/render which works just fine with chi.

your code will look like:

import renderPkg "github.com/unrolled/render"

var render *render.Render

func init() {
  render = renderPkg.New() // pass options if you want
}

func x() http.Handler {
  r := chi.New()
  r.Get("/", handler)
}

func handler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  // processing..
  render.JSON(w, 200, responseObj)
}

another suggestion, is wrap the unrolled/render package by making your own "render" package that is a part of your project, and set defaults there so its setup to use across packages.

The goals of chi are to stay minimal, allow full control without limitation of possibility or productivity. I guess the gap right now is that chi doesn't provide every library out of the box, you're expected to make your own choices for something like the responder. I will update the example to show how to wrap your own render responder.

Got it~ It looks elegant.

Was the example linked in https://github.com/pressly/chi/blob/master/_examples/rest/render/render.go integrated into rest/main.go?

So I'd like to understand if you prefer something like:

"render.RenderList(w, r, NewArticleListResponse(articles))

instead of something like unrolled/render does, based on interface{}...

Thanks for chi btw! :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

netsharec picture netsharec  路  6Comments

valsor picture valsor  路  5Comments

chenjie4255 picture chenjie4255  路  11Comments

didip picture didip  路  7Comments

Bartuz picture Bartuz  路  3Comments