Golang Key Value Bolt DB

go get github.com/boltdb/bolt
package main

import (
"fmt"
"log"
"time"
"github.com/boltdb/bolt"
)

const b = "MyBucket"

func main() {
db := open("my.db")
defer db.Close()

set(db, b, "love", "golang")
v := get(db, b, "love")
fmt.Printf("I love %s\n", v)
}

func open(file string) *bolt.DB {
db, err := bolt.Open(file, 0600, &bolt.Options{Timeout: 1 * time.Second})
if err != nil {
//handle error
log.Fatal(err)
}
return db
}

func set(db *bolt.DB, bucket, key, value string) {
db.Update(func(tx *bolt.Tx) error {
b, _ := tx.CreateBucketIfNotExists([]byte(bucket))
err := b.Put([]byte(key), []byte(value))
return err
})
}

func get(db *bolt.DB, bucket, key string) string {
s := ""
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucket))
s = string(b.Get([]byte(key)))
return nil
})
return s
}

func del(db *bolt.DB, bucket, key string) {
db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucket))
b.Delete([]byte(key))
return nil
})
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kevin FOO

Kevin FOO

A software engineer, a rock climbing, inline skating enthusiast, a husband, a father.