Created
November 29, 2018 08:25
-
-
Save zeddee/462feb0d3155a90ba5dfd2e9be2d3feb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"github.com/boltdb/bolt" | |
log "github.com/sirupsen/logrus" | |
) | |
func main() { | |
db, err := bolt.Open("./bolt.db", 0644, &bolt.Options{}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer db.Close() | |
bucket := "world" | |
key := "hello" | |
value := "hello world" | |
if err := put(db, bucket, key, value); err != nil { | |
log.Fatal(err) | |
} | |
if v, err := getValue(db, bucket, key); err != nil { | |
log.Fatal(err) | |
} else { | |
fmt.Println(v) | |
} | |
} | |
func put(db *bolt.DB, bucket, key, value string) error { | |
k := []byte(key) | |
v := []byte(value) | |
// Whenever we call a boltdb method, bolt passes a transaction object from the database to a receiving function. | |
// The receiving function takes the transaction object and makes method calls to it, depending on what you need it to do. | |
// QUESTION tho: since both the db.Update and db.View passes a bolt.Tx object of the same type, does that mean that | |
// they _are_ the same object, with the same methods available? | |
// ANSWER: Nope. db.Update() passes in a read-write Tx object. db.View() passes in a read-only Tx object. | |
err := db.Update(func(tx *bolt.Tx) error { | |
bucket, err := tx.CreateBucketIfNotExists([]byte(bucket)) | |
if err != nil { | |
return nil | |
} | |
if err := bucket.Put(k, v); err != nil { | |
return err | |
} | |
return nil | |
}) | |
if err != nil { | |
return err | |
} | |
return nil | |
} | |
func getValue(db *bolt.DB, bucket, key string) (string, error) { | |
k := []byte(key) | |
var val string | |
err := db.View(func(tx *bolt.Tx) error { | |
b := tx.Bucket([]byte(bucket)) | |
if b == nil { | |
return fmt.Errorf("Bucket %q not found", bucket) | |
} | |
val = string(b.Get(k)) | |
return nil | |
}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
return val, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment