Home > Backend Development > Golang > How to Achieve Custom BSON Marshaling in Go, Similar to Custom JSON Marshaling?

How to Achieve Custom BSON Marshaling in Go, Similar to Custom JSON Marshaling?

Patricia Arquette
Release: 2024-12-01 06:44:09
Original
763 people have browsed it

How to Achieve Custom BSON Marshaling in Go, Similar to Custom JSON Marshaling?

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template