Skip to content

Instantly share code, notes, and snippets.

@MasterAler
Forked from dwburke/unmarshal.defaults.go
Last active December 22, 2021 17:06
Show Gist options
  • Save MasterAler/9619269197d6dda18903f4707e4d1868 to your computer and use it in GitHub Desktop.
Save MasterAler/9619269197d6dda18903f4707e4d1868 to your computer and use it in GitHub Desktop.
Default values when unmarshalling JSON and YAML in Go
package main
import (
"encoding/json"
"fmt"
"os"
yaml "gopkg.in/yaml.v2"
)
type TestStruct struct {
SomeField string `json:"somefield" yaml:"somefield"`
OtherField string `json:"otherfield" yaml:"otherfield"`
Number int64 `json:"number" yaml:"number"`
}
// UnmarshalJSON is the implementation of the json.Unmarshaler interface.
func (t *TestStruct) UnmarshalJSON(data []byte) error {
type innerLol TestStruct
inner := &innerLol{
SomeField: "default value",
OtherField: "other default",
Number: 77,
}
if err := json.Unmarshal(data, inner); err != nil {
return err
}
*t = TestStruct(*inner)
return nil
}
// UnmarshalYAML is the implementation of the yaml.Unmarshaler interface.
func (t *TestStruct) UnmarshalYAML(unmarshal func(interface{}) error) error {
type innerLol TestStruct
inner := &innerLol{
SomeField: "default value",
OtherField: "other default",
Number: 77,
}
if err := unmarshal(inner); err != nil {
return err
}
*t = TestStruct(*inner)
return nil
}
func main() {
jsonData := []byte(`
{
"somefield": "fubar",
"otherfield": "yes"
}
`)
yamlData := []byte("somefield: \"fubar\"\nnumber: 66")
var sample1 TestStruct
err := json.Unmarshal(jsonData, &sample1)
if err != nil {
fmt.Println("An error occured: %v", err)
os.Exit(1)
}
var sample2 TestStruct
err = yaml.Unmarshal(yamlData, &sample2)
if err != nil {
fmt.Println("An error occured: %v", err)
os.Exit(1)
}
fmt.Printf("%+v\n", sample1)
fmt.Printf("%+v\n", sample2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment