Marshalling Go empty time into JSON

Suppose we have the following struct in your Go project.

type Blogpost struct {
    Title      string        `json:"title"`
    Tags      []string       `json:"tags"`
    CreatedAt  time.Time     `json:"created_at,omitempty"`
}

When we want to call an API to create a blogpost, we probably don't need to provide the CreatedAt field. But if we marshal the above struct without adding a data into CreatedAt, we would get the below result.

{"title":"Blog Title","tags":["first","second"],"created_at":"0001-01-01T00:00:00Z"}

Reason

So why does the omitempty does not work here?

Since time.Time is actually a struct, adding the omitempty tag will not work.

Solution

Use a time pointer instead for CreatedAt. For example:

package main

import (
    "encoding/json"
    "fmt"
    "time"
)

type Blogpost struct {
    Title     string     `json:"title"`
    Tags      []string   `json:"tags"`
    CreatedAt *time.Time `json:"created_at,omitempty"`
}

func main() {
    blogpost := Blogpost{
        Title: "Blog Title",
        Tags:  []string{"first", "second"},
    }
    var jsonData []byte
    jsonData, _ = json.Marshal(blogpost)
    fmt.Println(string(jsonData))
}

Result:

{"title":"Blog Title","tags":["first","second"]}