Go Struct Tags and the backtick

Today I stumbled upon a stuct tags in Go. I hadn’t heard or seen these before as they are barely mentioned in any go documentation, but they can be crucial to working with protobufs, json or xml.

In my case I was working with json.

I’m trying to write a command line uploader for pictures for gallery3, as there appears to be no client that actually works on linux. Gallery3 uses a RESTful api with the request contents being delivered in url encoded json.

Go has a really nice json package for getting json data in and out of Go structures. The problem I was running into was that the golang JSON package requires upper case names (i.e. exported names) for marshalling and unmarshalling data, while the actual JSON package needed by the rest api required lower case names.

Enter Struct Tags: http://weekly.golang.org/pkg/encoding/json/#Marshal

You can specify a different name than the one in the Go struct by “tagging” the structure field like this:

`json:”myName”`

Now, you look at that and ask: “Are those single quotes?”

No. They are backticks, also know as backquotes, also know as a grave, also known as that thing that’s on the same key as the tilde.

I had no idea that they even existed, much less were a lexically valid part of a golang program.

My structure ended up looking like this:

type RestCreate struct { Type string `json:”type”` Name string `json:”name”` Title string `json:”title”` }