Small introduction to tags in Go

July 21, 2015

Go has an awesome feature built in, namely tags. You are probably already familiar with them, they are like annotations in Java for example.

This is just a quick introduction: how to use them, and how to implement them.

First of all, a quick introduction to tags. Let’s take a look at the encoding/json package. This package makes use of tags for the marshalling and unmarshalling of structs/json.

A simple example:

type Post struct {
    Title    string `json:"title"`
    Views    int    `json:"pageviews"`
    Password string `json:"-"`

Because of these tags the JSON package knows that it will have to output a JSON that will look somewhat like this: { "title" : "My title", "pageviews" : 812 }

As you can see, it used the tags to produce the JSON output.

Now consider we want to build something like a validation package, that validates structs based on their tags. Imagine the following:

type Post struct {
    Title string `validation:"max_length=20 allow_blank=false"`
    Body  string `validation:"allow_blank=false"`

Now in order to be able to validate this struct, we will need to parse these tags first.

In order to be able to retrieve the tags of structs, we will be needing the reflect package.

The retrieval of tags is done as follows:

var post Post
modelType := reflect.TypeOf(post)

for i := 0; i < modelType.NumField(); i++ {
    field := modelType.Field(i)
    validation := field.Tag.Get("validation")

This will simply output the following:

max_length=20 allow_blank=false

You have now retrieved the tags for each field in the struct. From here on out you can apply whatever logic you want to apply to the struct and it’s tags, and process it in any way you see fit.

Get Machiel Mail in your inbox!

Of course I have a newsletter, all the cool kids have them! Sign up if you want to get notified of the occasional blog post I write. They will be mostly about Go, or simply about projects I am working on. And it might just turn out that they are interesting!

And if you're wondering, will he send sp... No, I will never send you any spam!

comments powered by Disqus