Skip to content

Instantly share code, notes, and snippets.

@dstaley
Created July 13, 2013 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dstaley/5992431 to your computer and use it in GitHub Desktop.
Save dstaley/5992431 to your computer and use it in GitHub Desktop.

Given the following JSON responses:

GET /things

{
    "things": [
        {
            "name": "spoon"
        },
        {
            "name": "fork"
        },
        {
            "name": "knife"
        }
    ]
}

GET /things/spoon

{
    "thing": {
        "name": "spoon"
    }
}

What's the best way to represent these two responses in Go? I was thinking of using three structs: a root struct for multiple things, a root struct for one thing, and struct for a singular thing.

type RootThings struct {
  Things []Thing `json:things`
}

type RootThing struct {
  Thing *Thing `json:thing`
}

type Thing struct {
  Name string `json:name`
}

Something about this feels dirty though :(

@paddycarver
Copy link

I would combine singular things and multiple things into

GET /things/oso

{
    "things": [
        {
            "name": "Oso"
        }
    ]
}

Then you can have (which is what I do):

type Thing struct {
    Name string `json:"name,omitempty"`
}

type Response struct {
    Things []Thing `json:"things,omitempty"`
}

Because empty items will be omitted, the Response object can (and should) be global for all request. No matter what request is made, it should have a Response object returned.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment