/resolvy

Struct marshalling made even easier

Primary LanguageGoMIT LicenseMIT

resolvy

Contents

Installation

To use resolvy, you need to have Go installed and set up.

Now, you can get resolvy by running

$ go get -u github.com/daspoet/resolvy

and import it in your code:

import "github.com/daspoet/resolvy"

Getting started

To understand how to register custom resolvers on a type with resolvy, let's look at the following example:

Suppose we have a struct

import "time"

type Message struct {
    Timestamp time.Time `json:"timestamp,omitempty"`
    Author    string    `json:"author,omitempty"`
}

that we would like to marshal into JSON while also formatting its Timestamp field. While the standard library allows us to make Message implement the json.Marshaler interface

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

type Message struct {
    Timestamp time.Time
    Author    string    
}

func (msg Message) MarshalJSON() ([]byte, error) {
    return json.Marshal(struct {
        Timestamp string `json:"timestamp,omitempty"`
        Author    string `json:"author,omitempty"`
    }{
        Timestamp: msg.Timestamp.Format(time.RFC850),
        Author:    msg.Author,
    })
}

we can immediately see that this is problematic, because we have to list all the fields we don't want to alter the marshalled representation of alongside the Timestamp field. This obscures our original intent to anyone trying to understand our code.

To solve this problem, resolvy allows us to register custom marshalers on specific fields of a struct type. Using resolvy, we can simplify our code:

import (
    "encoding/json",
    "github.com/daspoet/resolvy",
    "time"
)

type Message struct {
    Timestamp time.Time `resolvy:"timestamp,omitempty"`
    Author    string    `resolvy:"author,omitempty"`
}

func (msg Message) MarshalJSON() ([]byte, error) {
    return resolvy.MarshalJSON(msg, resolvy.MarshalConfig{
        Marshalers: map[string]resolvy.FieldMarshaler{
            "timestamp": func() (interface{}, error) {
                return msg.Timestamp.Format(time.RFC850), nil
            },
        },
    })
}