Home > Backend Development > Golang > How to Implement Custom BSON Marshaling in Go?

How to Implement Custom BSON Marshaling in Go?

Linda Hamilton
Release: 2024-11-28 03:02:14
Original
345 people have browsed it

How to Implement Custom BSON Marshaling in Go?

Custom BSON Marshaling

Custom BSON marshaling is similar to custom JSON marshaling, but you'll need to implement the bson.Getter and bson.Setter interfaces instead. These interfaces allow you to define how your custom type should be converted to and from BSON data.

For example, let's say you have a Currency type that requires custom marshaling:

package yourpackage

import (
    "context"
    "errors"

    "github.com/globalsign/mgo/bson"
    "github.com/shopspring/decimal"
)

type Currency struct {
    Value        decimal.Decimal
    CurrencyCode string
}

func (c Currency) GetBSON() (interface{}, error) {
    if c.CurrencyCode == "" {
        return nil, errors.New("CurrencyCode cannot be empty")
    }

    return bson.M{
        "value":        c.Value.String(),
        "currencyCode": c.CurrencyCode,
    }, nil
}

func (c *Currency) SetBSON(raw bson.Raw) error {
    var m bson.M

    if err := raw.Unmarshal(&m); err != nil {
        return err
    }

    val, ok := m["value"]
    if !ok {
        return errors.New("missing 'value' field in BSON data")
    }

    c.Value, _ = decimal.NewFromString(val.(string))

    code, ok := m["currencyCode"]
    if !ok {
        return errors.New("missing 'currencyCode' field in BSON data")
    }

    c.CurrencyCode, _ = code.(string)

    return nil
}
Copy after login

With this implementation, you can now register your custom Currency type with the MGO BSON encoder:

session := mgo.Dial("mongodb://localhost:27017")
defer session.Close()

session.SetCollectionValidator("products",{
    "validator":{
        "$jsonSchema":{
            "bsonType":"object",
            "required":["name","code","price"],
            "properties":{
                "name":{"bsonType":"string"},
                "code":{"bsonType":"string"},
                "price":{
                    "bsonType":"object",
                    "required":["value", "currencyCode"],
                    "properties":{
                        "value":{"bsonType":"string", "pattern":"^[0-9,]+(.[0-9,]+)?$"},
                        "currencyCode":{"bsonType":"string", "enum":["USD", "EUR", "GBP"]},
                    },
                },
            }
        }
    }
})

collection := session.DB("products").C("products")
Copy after login

Now, when you save a document with a Currency field to MongoDB, the MGO encoder will automatically use your custom marshaling function to convert the Currency to BSON.

Note that this is just one example of how you can add custom marshaling for BSON types. The specific implementation will vary depending on the requirements of your particular application.

The above is the detailed content of How to Implement Custom BSON Marshaling in Go?. 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