Created
March 1, 2016 20:56
-
-
Save abh1nav/ce2993036cf84f58f919 to your computer and use it in GitHub Desktop.
This file contains 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" | |
"log" | |
"github.com/boltdb/bolt" | |
) | |
var bucketName = []byte("bucket") | |
func main() { | |
db, err := bolt.Open("my.db", 0600, nil) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer db.Close() | |
err = db.Update(func(tx *bolt.Tx) error { | |
_, err := tx.CreateBucket(bucketName) | |
return err | |
}) | |
if err != nil { | |
log.Fatalf("create bucket: %s", err.Error()) | |
} | |
err = put(db, "test", "abcd") | |
if err != nil { | |
log.Fatalf("put: %s", err.Error()) | |
} | |
val := get(db, "test") | |
fmt.Println(string(val)) | |
for i := 0; i <= 1000; i++ { | |
put(db, fmt.Sprintf("test%d", i), fmt.Sprintf("val%d", i)) | |
} | |
for i := 0; i <= 1000; i++ { | |
get(db, fmt.Sprintf("test%d", i)) | |
} | |
fmt.Println(string(val)) | |
} | |
func get(db *bolt.DB, key string) (val []byte) { | |
db.View(func(tx *bolt.Tx) error { | |
b := tx.Bucket(bucketName) | |
val = b.Get([]byte(key)) | |
return nil | |
}) | |
return val | |
} | |
func put(db *bolt.DB, key, value string) error { | |
return db.Update(func(tx *bolt.Tx) error { | |
b := tx.Bucket(bucketName) | |
// Persist bytes to users bucket. | |
return b.Put([]byte(key), []byte(value)) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment