duanjurong1347 2016-03-31 02:09
浏览 357
已采纳

在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

  • 写回答

1条回答 默认 最新

  • dongyan9838 2016-03-31 03:06
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)