db.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/bolt-master"
  6. )
  7. type boltdb struct {
  8. mdb *bolt.DB
  9. }
  10. var db boltdb
  11. func (m *boltdb) initBoltDb() bool {
  12. var err error
  13. var dbpath string
  14. dbPathLen := len(Gconfig.DB.DbPath)
  15. if Gconfig.DB.DbPath[dbPathLen-1] == '/' {
  16. dbpath = fmt.Sprintf("%scoinproxy.db", Gconfig.DB.DbPath)
  17. } else {
  18. dbpath = fmt.Sprintf("%s/coinproxy.db", Gconfig.DB.DbPath)
  19. }
  20. log.Debug("dbpath:%s", dbpath)
  21. m.mdb, err = bolt.Open(dbpath, 0600, &bolt.Options{Timeout: 1 * time.Second})
  22. if err != nil {
  23. fmt.Println(err)
  24. return false
  25. }
  26. tx, err := m.mdb.Begin(true)
  27. if err != nil {
  28. fmt.Printf("mdb err:%s\n", err.Error())
  29. return false
  30. }
  31. _, err = tx.CreateBucketIfNotExists([]byte(BucketSC))
  32. if err != nil {
  33. fmt.Printf("create bucket err:%s\n", err.Error())
  34. return false
  35. }
  36. if err := tx.Commit(); err != nil {
  37. return false
  38. }
  39. return true
  40. }
  41. func (m *boltdb) Put(bucket string, key, value []byte) error {
  42. err := m.mdb.Update(func(tx *bolt.Tx) error {
  43. b := tx.Bucket([]byte(bucket))
  44. err := b.Put(key, value)
  45. return err
  46. })
  47. return err
  48. }
  49. func (m *boltdb) Get(bucket string, key []byte) ([]byte, error) {
  50. var v []byte
  51. err := m.mdb.View(func(tx *bolt.Tx) error {
  52. b := tx.Bucket([]byte(bucket))
  53. v = b.Get(key)
  54. fmt.Printf("value:%s\n", string(v))
  55. return nil
  56. })
  57. return v, err
  58. }
  59. func (m *boltdb) Del(buckets string, key []byte) error {
  60. err := m.mdb.Update(func(tx *bolt.Tx) error {
  61. b := tx.Bucket([]byte(buckets))
  62. err := b.Delete(key)
  63. return err
  64. })
  65. return err
  66. }