zergon321

BoltDB example

Sep 23rd, 2020 (edited)
800
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "bytes"
  5.     "encoding/gob"
  6.     "fmt"
  7.  
  8.     "github.com/boltdb/bolt"
  9. )
  10.  
  11. // Person is a type
  12. // whose objects are
  13. // to be saved in the
  14. // database.
  15. type Person struct {
  16.     Name    string
  17.     Surname string
  18.     Age     int
  19. }
  20.  
  21. func main() {
  22.     // Open the database.
  23.     db, err := bolt.Open("people.db", 0666, nil)
  24.     handleError(err)
  25.  
  26.     // Create a new data
  27.     // structure to store in the
  28.     // database.
  29.     person := &Person{
  30.         Name:    "John",
  31.         Surname: "Doe",
  32.         Age:     38,
  33.     }
  34.  
  35.     // Put the structure in the collection.
  36.     err = db.Update(func(tx *bolt.Tx) error {
  37.         buck, err := tx.CreateBucket([]byte("people"))
  38.  
  39.         if err != nil {
  40.             return err
  41.         }
  42.  
  43.         buffer := bytes.NewBuffer([]byte{})
  44.         encoder := gob.NewEncoder(buffer)
  45.  
  46.         err = encoder.Encode(person)
  47.  
  48.         if err != nil {
  49.             return err
  50.         }
  51.  
  52.         data := buffer.Bytes()
  53.         err = buck.Put([]byte("lol"), data)
  54.  
  55.         return err
  56.     })
  57.     handleError(err)
  58.  
  59.     // Extract data from the database.
  60.     restored := new(Person)
  61.     err = db.View(func(tx *bolt.Tx) error {
  62.         buck := tx.Bucket([]byte("people"))
  63.  
  64.         if buck == nil {
  65.             return fmt.Errorf("no bucket called \"people\"")
  66.         }
  67.  
  68.         data := buck.Get([]byte("lol"))
  69.  
  70.         if data == nil {
  71.             return fmt.Errorf("no key \"lol\"")
  72.         }
  73.  
  74.         buffer := bytes.NewBuffer(data)
  75.         decoder := gob.NewDecoder(buffer)
  76.         err := decoder.Decode(restored)
  77.  
  78.         return err
  79.     })
  80.  
  81.     fmt.Println("Extracted data:", restored)
  82. }
  83.  
  84. func handleError(err error) {
  85.     if err != nil {
  86.         panic(err)
  87.     }
  88. }
  89.  
RAW Paste Data