Home >Backend Development >Golang >How to Implement Custom BSON Marshalling for a Go Struct?
In Go, developers often encounter scenarios where they require custom marshalling and unmarshalling functionality for complex data structures. When working with BSON, MongoDB's binary data format, the need for custom marshalling arises. The article introduces the concept of defining custom BSON marshaling through the Getter and Setter interfaces.
Specifically, the question focuses on how to write custom BSON marshalling for a Currency struct that encapsulates a currency value and a currency code. The MarshalJSON and UnmarshalJSON methods are demonstrated as effective approaches for custom JSON marshalling and unmarshalling. However, finding documentation on BSON marshalling can be challenging.
To achieve custom BSON marshalling, the Currency struct must implement the bson.Getter and bson.Setter interfaces. The GetBSON method returns a BSON-friendly representation of the Currency struct, and the SetBSON method sets the value of the Currency struct based on the provided BSON data. The code below demonstrates these implementations:
type Currency struct { value decimal.Decimal //The actual value of the currency. currencyCode string //The ISO currency code. } // GetBSON implements bson.Getter. func (c Currency) GetBSON() (interface{}, error) { f := c.Value().Float64() return struct { Value float64 `json:"value" bson:"value"` CurrencyCode string `json:"currencyCode" bson:"currencyCode"` }{ Value: f, CurrencyCode: c.currencyCode, }, nil } // SetBSON implements bson.Setter. func (c *Currency) SetBSON(raw bson.Raw) error { decoded := new(struct { Value float64 `json:"value" bson:"value"` CurrencyCode string `json:"currencyCode" bson:"currencyCode"` }) bsonErr := raw.Unmarshal(decoded) if bsonErr == nil { c.value = decimal.NewFromFloat(decoded.Value) c.currencyCode = decoded.CurrencyCode return nil } else { return bsonErr } }
By implementing these methods, developers can now use the Currency struct seamlessly with MongoDB, allowing for custom marshalling and unmarshalling of currency data.
The above is the detailed content of How to Implement Custom BSON Marshalling for a Go Struct?. For more information, please follow other related articles on the PHP Chinese website!