Go

Default values when unmarshal json in go

go

If we want to unmarshal a json into a struct, and we want to have default values if a value is absent in the json, the following code can be used: type LogEndpoint struct { MaxLogLevel int `json:"max_log_level"` } func (o *LogEndpoint) UnmarshalJSON(text []byte) error { type defaults LogEndpoint opts := defaults{ MaxLogLevel: 5, } if err := json.Unmarshal(text, &opts); err != nil { return err } *o = LogEndpoint(opts) return nil } The code provides a method called UnmarshalJSON that belongs to a struct called LogEndpoint.

Learning go


edited on Feb 22, 2024
go

This entry contains great learning materials for go. Starting A Tour of Go: At the very beginning, you can start with A Tour of Go. This is a go tutorial that allows you to learn and run go code directly in your Browser. Also, the Tour can be downloaded to take it offline. golang-standards: For beginners, it’s not so clear how to structure a go repository. The following link gives a good introduction.