To encode and decode data in binary formats like BSON in Go, you can use the gopkg.in/mgo.v2/bson
package.
Here's an example of how to encode and decode data in BSON format:
gopkg.in/mgo.v2
package using the following command:go get gopkg.in/mgo.v2/bson
gopkg.in/mgo.v2/bson
package in your Go source file:import (
"fmt"
"gopkg.in/mgo.v2/bson"
)
type Person struct {
Name string
Age int
}
person := Person{"John Doe", 30}
bsonData, err := bson.Marshal(person)
if err != nil {
fmt.Println("Error encoding BSON:", err)
return
}
var decodedPerson Person
err = bson.Unmarshal(bsonData, &decodedPerson)
if err != nil {
fmt.Println("Error decoding BSON:", err)
return
}
fmt.Println(decodedPerson.Name) // Prints: "John Doe"
fmt.Println(decodedPerson.Age) // Prints: 30
That's it! You have successfully encoded your data into BSON format and decoded it back into your Go struct using the gopkg.in/mgo.v2/bson
package.