How to encode and decode data in binary formats (e.g., BSON) in Go?

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:

  1. Install the gopkg.in/mgo.v2 package using the following command:
go get gopkg.in/mgo.v2/bson
  1. Import the gopkg.in/mgo.v2/bson package in your Go source file:
import ( "fmt" "gopkg.in/mgo.v2/bson" )
  1. Define a struct to represent your data:
type Person struct { Name string Age int }
  1. Encode the data into BSON format:
person := Person{"John Doe", 30} bsonData, err := bson.Marshal(person) if err != nil { fmt.Println("Error encoding BSON:", err) return }
  1. Decode the BSON data back into your struct:
var decodedPerson Person err = bson.Unmarshal(bsonData, &decodedPerson) if err != nil { fmt.Println("Error decoding BSON:", err) return }
  1. Access the decoded data:
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.