在BoltDB中存储数据的最佳方法
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
我是BoltDB和Golang的新手,并试图寻求帮助。 p> 所以,我了解到我只能保存BoltDB的键和值的字节数组([] byte)。 如果我具有以下用户结构,并且键将是用户名,那么将数据存储到期望字节数组的BoltDB中的最佳选择是什么? p>
将其序列化或JSON? 还是更好的方法? p>
type用户结构{
名称字符串
年龄int
位置字符串
密码字符串
地址字符串
}
code > pre>
非常感谢,晚上好! p>
div>
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
}