package main import ( "log" "github.com/boltdb/bolt" ) func main() { // Open the database file. db, err := bolt.Open("my.db", 0600, nil) if err != nil { log.Fatal(err) } defer db.Close() // Start a new read-write transaction. tx, err := db.Begin(true) if err != nil { log.Fatal(err) } defer tx.Rollback() // Create a bucket. _, err = tx.CreateBucketIfNotExists([]byte("MyBucket")) if err != nil { log.Fatal(err) } // Commit the transaction and check for errors. if err := tx.Commit(); err != nil { log.Fatal(err) } }
// Start a read-only transaction. tx, err := db.Begin(false) if err != nil { log.Fatal(err) } defer tx.Rollback() // Open the "MyBucket" bucket. b := tx.Bucket([]byte("MyBucket")) // If the bucket doesn't exist, log an error and return. if b == nil { log.Printf("bucket %q not found", "MyBucket") return } // Get the value for the key "mykey". v := b.Get([]byte("mykey")) // If the value is nil, log an error and return. if v == nil { log.Printf("key %q not found in bucket %q", "mykey", "MyBucket") return } // Print the value to the console. fmt.Printf("mykey=%s\n", v)In this example, we first start a read-only transaction using `Begin(false)`. We then open the `MyBucket` bucket using the `Bucket` method on the `Tx` struct. Finally, we get the value associated with the key `mykey` using the `Get` method on the bucket. If the value is non-nil, we print it to the console. As you may have noticed, both examples rely on the `Tx` struct and `Bucket` struct from the `github.com.boltdb.bolt` package.