Tip Golang with EmberJS - JSON Response

If you are search a article step-by-step there are 3 good post by @nerdyworm

Building an App With Ember.js and Go - Part 1

Building an App With Ember.js and Go - Part 2

Building an App With Ember.js and Go - Part 3

This post is about my short experience to build uhura, a podcasts manager. Let’s go!

On API side, I’ll use martini with render package and I have a model called Channel, the initial api code show like it:

package main

import (
    "github.com/codegangsta/martini"
    "github.com/codegangsta/martini-contrib/render"
)

type Channel struct {
    Id          int
    Title       string
    Description string
}

func main() {
    chs := make([]Channel, 2)
    chs[0] = Channel{Id: 1, Title: "First", Description: "Me"}
    chs[1] = Channel{Id: 2, Title: "Second", Description: "You"}

    m := martini.Classic()
    m.Use(render.Renderer())
    m.Get("/api/channels", func(r render.Render) {
        r.JSON(200, chs)
    })
    m.Run()
}

JSON Response Structure #

The initial code above doesn’t work with Ember, because doesn’t agree with the DS.RESTAdapter JSON Conventions.

It’s simple to fix it, on response send the model root, on example, channels, see:

m.Get("/api/channels", func(r render.Render) {
    r.JSON(200, map[string]interface{}{"channels": chs})
})

The other thing is about name attributes, send simply a golang struct, decoded by json.Decode, generates all name attributes capitalised like this:

{
  channels: [
    {
      Id: 1,
      Title: "First",
      Description: "Me"
    },
    {
      Id: 2,
      Title: "Second",
      Description: "You"
    }
  ]
}

We’ll use Struct Tag to fixed it:

type Channel struct {
    Id          int    `json:"id"`
    Title       string `json:"title"`
    Description string `json:"description"`
}

Now response json is correct and good to ember:

{
  channels: [
    {
      id: 1,
      title: "First",
      description: "Me"
    },
    {
      id: 2,
      title: "Second",
      description: "You"
    }
  ]
}

The basic config on ember to works now, it only set DS.RESTAdapter to ApplicationAdapter with namespace api

var App = Ember.Application.create();
App.ApplicationAdapter = DS.RESTAdapter.extend({
  namespace: 'api'
});

App.Channel = DS.Model.extend({
  title: DS.attr('string'),
  description: DS.attr('string')
});

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return App.Channel.find();
  }
});

That’s all folks! Feel free to send question or suggestion, Thanks!

 
86
Kudos
 
86
Kudos

Now read this

Manage golang dependencies

Using golang in these 2 months I think the most hard thing is manage dependencies, when I use golang only to test or have fun, normally, I don’t worries with dependencies problems. On Ruby, Java, Python and Nodejs ecosystem have (good)... Continue →