首页 > 其他分享 >boltdb example

boltdb example

时间:2023-05-23 20:44:33浏览次数:40  
标签:boltdb err nil db time byte example log

源码链接:https://github.com/zupzup/boltdb-example.git

package main

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

// Config type
type Config struct {
    Height   float64   `json:"height"`
    Birthday time.Time `json:"birthday"`
}

// Entry type
type Entry struct {
    Calories int    `json:"calories"`
    Food     string `json:"food"`
}

func main() {
    db, err := setupDB()
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    conf := Config{Height: 186.0, Birthday: time.Now()}
    err = setConfig(db, conf)
    if err != nil {
        log.Fatal(err)
    }
    err = addWeight(db, "85.0", time.Now())
    if err != nil {
        log.Fatal(err)
    }
    err = addEntry(db, 100, "apple", time.Now())
    if err != nil {
        log.Fatal(err)
    }

    err = addEntry(db, 100, "orange", time.Now().AddDate(0, 0, -2))
    if err != nil {
        log.Fatal(err)
    }

    err = db.View(func(tx *bolt.Tx) error {
        conf := tx.Bucket([]byte("DB")).Get([]byte("CONFIG"))
        fmt.Printf("Config: %s\n", conf)
        return nil
    })
    if err != nil {
        log.Fatal(err)
    }

    err = db.View(func(tx *bolt.Tx) error {
        b := tx.Bucket([]byte("DB")).Bucket([]byte("WEIGHT"))
        b.ForEach(func(k, v []byte) error {
            fmt.Println(string(k), string(v))
            return nil
        })
        return nil
    })
    if err != nil {
        log.Fatal(err)
    }

    err = db.View(func(tx *bolt.Tx) error {
        c := tx.Bucket([]byte("DB")).Bucket([]byte("ENTRIES")).Cursor()
        min := []byte(time.Now().AddDate(0, 0, -7).Format(time.RFC3339))
        max := []byte(time.Now().AddDate(0, 0, 0).Format(time.RFC3339))
        for k, v := c.Seek(min); k != nil && bytes.Compare(k, max) <= 0; k, v = c.Next() {
            fmt.Println(string(k), string(v))
        }
        return nil
    })
    if err != nil {
        log.Fatal(err)
    }
}

func setupDB() (*bolt.DB, error) {
    db, err := bolt.Open("test.db", 0600, nil)
    if err != nil {
        return nil, fmt.Errorf("could not open db, %v", err)
    }
    err = db.Update(func(tx *bolt.Tx) error {
        root, err := tx.CreateBucketIfNotExists([]byte("DB"))
        if err != nil {
            return fmt.Errorf("could not create root bucket: %v", err)
        }
        _, err = root.CreateBucketIfNotExists([]byte("WEIGHT"))
        if err != nil {
            return fmt.Errorf("could not create weight bucket: %v", err)
        }
        _, err = root.CreateBucketIfNotExists([]byte("ENTRIES"))
        if err != nil {
            return fmt.Errorf("could not create days bucket: %v", err)
        }
        return nil
    })
    if err != nil {
        return nil, fmt.Errorf("could not set up buckets, %v", err)
    }
    fmt.Println("DB Setup Done")
    return db, nil
}

func setConfig(db *bolt.DB, config Config) error {
    confBytes, err := json.Marshal(config)
    if err != nil {
        return fmt.Errorf("could not marshal config json: %v", err)
    }
    err = db.Update(func(tx *bolt.Tx) error {
        err = tx.Bucket([]byte("DB")).Put([]byte("CONFIG"), confBytes)
        if err != nil {
            return fmt.Errorf("could not set config: %v", err)
        }
        return nil
    })
    fmt.Println("Set Config")
    return err
}

func addWeight(db *bolt.DB, weight string, date time.Time) error {
    err := db.Update(func(tx *bolt.Tx) error {
        err := tx.Bucket([]byte("DB")).Bucket([]byte("WEIGHT")).Put([]byte(date.Format(time.RFC3339)), []byte(weight))
        if err != nil {
            return fmt.Errorf("could not insert weight: %v", err)
        }
        return nil
    })
    fmt.Println("Added Weight")
    return err
}

func addEntry(db *bolt.DB, calories int, food string, date time.Time) error {
    entry := Entry{Calories: calories, Food: food}
    entryBytes, err := json.Marshal(entry)
    if err != nil {
        return fmt.Errorf("could not marshal entry json: %v", err)
    }
    err = db.Update(func(tx *bolt.Tx) error {
        err := tx.Bucket([]byte("DB")).Bucket([]byte("ENTRIES")).Put([]byte(date.Format(time.RFC3339)), entryBytes)
        if err != nil {
            return fmt.Errorf("could not insert entry: %v", err)
        }

        return nil
    })
    fmt.Println("Added Entry")
    return err
}

运行结果:

#go run main.go
DB Setup Done
Set Config
Added Weight
Added Entry
Added Entry
Config: {"height":186,"birthday":"2023-05-23T20:34:37.185488195+08:00"}
2023-05-23T20:34:37+08:00 85.0
2023-05-21T20:34:37+08:00 {"calories":100,"food":"orange"}
2023-05-23T20:34:37+08:00 {"calories":100,"food":"apple"}

 

 

标签:boltdb,err,nil,db,time,byte,example,log
From: https://www.cnblogs.com/wangjq19920210/p/17426336.html

相关文章

  • [React Typescript] Useful React Prop Type Examples
    RelevantforcomponentsthatacceptotherReactcomponentsasprops.exportdeclareinterfaceAppProps{children?:React.ReactNode;//best,acceptseverythingReactcanrenderchildrenElement:JSX.Element;//AsingleReactelementstyle?:React.C......
  • 关于STM32Cube_FW_F1_V1.8.0内的example顶层程序设计逻辑 与 RTC_Calendar增补
     Examples内程序结构STM32Cube_FW_F1_V1.8.0\Projects\STM3210E_EVAL\Examples内程序结构分析如下:使用外设XXX向工程添加 stm32f10x_XXX.c修改stm32f10x_conf.h 在stm32f1xx_hal_msp.c中写 外设XXX写初始化程序在stm32f1xx_it.c中写中断服务程序在main.c中写配置程......
  • docker compose fullstack example -- keycloak web grant-type: password
    fastapi-react-postgres-keycloak-ssohttps://github.com/fanqingsong/fastapi-react-postgres-keycloak-sso version:"3"services:nginx:image:nginx:1.17volumes:-./nginx/nginx.conf:/etc/nginx/conf.d/default.conf-./log......
  • Keycloak: Authorization Code Grant Example
    Keycloak:AuthorizationCodeGrantExamplehttps://www.appsdeveloperblog.com/keycloak-authorization-code-grant-example/ 适合web应用 Inthistutorial,youwilllearnhowtogetanaccesstokenfromtheKeycloakauthorizationserverusingtheOAuthAuthor......
  • Goroutines example
    一个入门的goroutines例子packagemainimport("fmt""time")funcf(fromstring){fori:=0;i<3;i++{fmt.Println(from,":",i)}}funcmain(){f("direct")gof("gorout......
  • 详细的BoltDB学习记录文档
    最近项目中用到了boltdb这个go开发的key/value数据库,但是之前并有接触过,所以特意去看了官方,也找了些资料,网上找的资料要不就是官方文档的翻译,要不就是简单的介绍一点,都不是很全,所以这里记录下。话不多说,冲!本篇文章是参考了官方的文档,内容和官方的基本一致,只是加了些自己的理解......
  • Tool-CMake-A Simple CMake Example
    Tool-CMake-ASimpleCMakeExamplehttps://cmake.org/examples/Therearethreedirectoriesinvolved.Thetopleveldirectoryhastwosubdirectoriescalled./Demoand./Hello.Inthedirectory./Hello,alibraryisbuilt.Inthedirectory./Demo,anexecuta......
  • 10 iozone Examples for Disk I/O Performance Measurement on Linux
    https://www.thegeekstuff.com/2011/05/iozone-examples/ Aswediscussedinour Linuxperformancemonitoringintroduction article,measuringIOsubsystemperformanceisveryimportant.Ifsomeoneiscomplainingthatadatabase(oranyapplication)running......
  • 论文解读(FGSM)《Explaining and Harnessing Adversarial Examples》
    论文信息论文标题:ExplainingandHarnessingAdversarialExamples论文作者:IanJ.Goodfellow,JonathonShlens,ChristianSzegedy论文来源:ICLR2015论文地址:download 论文代码:download视屏讲解:click1 介绍对抗攻击2方法扰动:$\eta=\varepsilon\operat......
  • cmake string example
    string(CONCATresult${var1}"/how")string(FIND${var1}"targetPattern"foundResultIndex)if(${foundResultIndex}GREATER_EQUAL0)endif()string(LENGTH<string><output_variable>)https://cmake.org/cmake/help/lates......