Golang Key Value Bolt DB

In my previous story on Go/Golang concurrent map, I was saving my data in a non persistent variable where all the data saved will be lost if I kill my Go/Golang process.

I stumble upon a key value database named Bolt which codes I had simplified. Integrating these below into the concurrent map example I should get a persistent concurrent map.

To install Bolt DB, run the command below

go get github.com/boltdb/bolt

Simplified codes below

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
})
}

Function names are pretty much self explanatory.

Open(file) — opens the database file saving the persistent data.

Set(database, bucket, key, value) —sets the value in the key in its respective database and bucket. A database can have multiple unique buckets, and a bucket can have multiple unique keys.

Get(database, bucket, key) — gets the value in the key in its respective database and bucket.

< Back to all the stories I had written

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