Custom BSON Marshaling: Equivalents for Custom JSON Marshaling
To achieve custom BSON marshaling, similar to the custom JSON marshaling demonstrated with the Currency struct, you can utilize the bson.Getter and bson.Setter interfaces. These interfaces allow for the customization of how values are encoded and decoded in BSON format.
Implementing Custom BSON Getter and Setter
The Currency struct can be updated to implement the bson.Getter and bson.Setter interfaces as follows:
// Currency struct implements bson.Getter and bson.Setter type Currency struct { value decimal.Decimal currencyCode string } // GetBSON implements bson.Getter. func (c Currency) GetBSON() (interface{}, error) { value := c.Value().Float64() return struct { Value float64 `json:"value" bson:"value"` CurrencyCode string `json:"currencyCode" bson:"currencyCode"` }{ Value: value, 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 { return bsonErr } c.value = decimal.NewFromFloat(decoded.Value) c.currencyCode = decoded.CurrencyCode return nil }
Using Custom BSON Marshaling in Parent Structs
Once the Currency struct is updated, similar to the custom JSON marshaling, the Product struct that embeds the Currency field will automatically use the custom marshaling when calling mgo.Marshal or bson.Encode. The output BSON will contain the desired field names and data values without the need for a separate struct with exported fields.
The above is the detailed content of How to Achieve Custom BSON Marshaling in Go, Similar to Custom JSON Marshaling?. For more information, please follow other related articles on the PHP Chinese website!