Best way to store data in BoltDB
Asked Answered
C

2

14

I am new to BoltDB and Golang, and trying to get your help.

So, I understand that I can only save byte array ([]byte) for key and value of BoltDB. If I have a struct of user as below, and key will be the username, what would be the best choice to store the data into BoltDB where it expects array of bytes?

Serializing it or JSON? Or better way?

type User struct {
    name string
    age  int
    location string
    password string
    address string 
}

Thank you so much, have a good evening

Clueless answered 31/3, 2016 at 2:9 Comment(1)
Good BoltDB example using json or gob encodingPresentative
T
21

Yes, I would recommend marshaling the User struct to JSON and then use a unique key []byte slice. Don't forget that marshaling to JSON only includes the exported struct fields, so you'll need to change your struct as shown below.

For another example, see the BoltDB GitHub page.

type User struct {
    Name string
    Age  int
    Location string
    Password string
    Address string 
}

func (user *User) save(db *bolt.DB) error {
    // Store the user model in the user bucket using the username as the key.
    err := db.Update(func(tx *bolt.Tx) error {
        b, err := tx.CreateBucketIfNotExists(usersBucket)
        if err != nil {
            return err
        }    

        encoded, err := json.Marshal(user)
        if err != nil {
            return err
        }
        return b.Put([]byte(user.Name), encoded)
    })
    return err
}
Trinitarianism answered 31/3, 2016 at 3:6 Comment(2)
Thank you for your help! Very helpful!Clueless
You also may want to look into other serialization formats like Protocol Buffers which can be significantly faster to marshal/unmarshal and provide features like versioning.Gatling
B
1

A good option is the Storm package, which allows for exactly what you are wanting to do:

package main

import (
   "fmt"
   "github.com/asdine/storm/v3"
)

type user struct {
   ID int `storm:"increment"`
   address string
   age int
}

func main() {
   db, e := storm.Open("storm.db")
   if e != nil {
      panic(e)
   }
   defer db.Close()
   u := user{address: "123 Main St", age: 18}
   db.Save(&u)
   fmt.Printf("%+v\n", u) // {ID:1 address:123 Main St age:18}
}

As you can see, you don't have to worry about marshalling, it takes care of it for you. By default it uses JSON, but you can configure it to use GOB or others as well:

https://github.com/asdine/storm

Balliett answered 30/12, 2020 at 15:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.