mirror of
https://github.com/schollz/cowyo.git
synced 2023-08-10 21:13:00 +03:00
2174edd471
Former-commit-id: a9b40f31f0753157af8500353395274b474642a2 [formerly 57875519283c5bfbfa6d852a27d72dc091157faa] [formerly bc0dde2306cf0e189d69349f344dffda393de1cc [formerly aecad9ba02f4aa09f9aef5add7df035e91e4b1a3 [formerly19aaf7bb44
]]] Former-commit-id: eb77f04e333250fef6799da788b460b77468dddf [formerly c3ddbc51302fbb8fc89410f114013b3a19f33cb8] Former-commit-id: 814d1b257f6529e8ec45ba7acfa7269967900397 Former-commit-id:6f445a7668
106 lines
1.8 KiB
Go
106 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"path"
|
|
"runtime"
|
|
"time"
|
|
|
|
"github.com/boltdb/bolt"
|
|
)
|
|
|
|
var db *bolt.DB
|
|
var open bool
|
|
|
|
// Open to create the database and open
|
|
func Open() error {
|
|
var err error
|
|
_, filename, _, _ := runtime.Caller(0) // get full path of this file
|
|
dbfile := path.Join(path.Dir(filename), "data.db")
|
|
config := &bolt.Options{Timeout: 30 * time.Second}
|
|
db, err = bolt.Open(dbfile, 0600, config)
|
|
if err != nil {
|
|
fmt.Println("Opening BoltDB timed out")
|
|
log.Fatal(err)
|
|
}
|
|
open = true
|
|
return nil
|
|
}
|
|
|
|
// Close database
|
|
func Close() {
|
|
open = false
|
|
db.Close()
|
|
}
|
|
|
|
// Data for storing in DB
|
|
type CowyoData struct {
|
|
Title string
|
|
Text string
|
|
}
|
|
|
|
func (p *CowyoData) load() error {
|
|
if !open {
|
|
return fmt.Errorf("db must be opened before saving!")
|
|
}
|
|
err := db.View(func(tx *bolt.Tx) error {
|
|
var err error
|
|
b := tx.Bucket([]byte("datas"))
|
|
if b == nil {
|
|
return nil
|
|
}
|
|
k := []byte(p.Title)
|
|
val := b.Get(k)
|
|
if val == nil {
|
|
return nil
|
|
}
|
|
err = p.decode(val)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
fmt.Printf("Could not get CowyoData: %s", err)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (p *CowyoData) save() error {
|
|
if !open {
|
|
return fmt.Errorf("db must be opened before saving")
|
|
}
|
|
err := db.Update(func(tx *bolt.Tx) error {
|
|
bucket, err := tx.CreateBucketIfNotExists([]byte("datas"))
|
|
if err != nil {
|
|
return fmt.Errorf("create bucket: %s", err)
|
|
}
|
|
enc, err := p.encode()
|
|
if err != nil {
|
|
return fmt.Errorf("could not encode CowyoData: %s", err)
|
|
}
|
|
err = bucket.Put([]byte(p.Title), enc)
|
|
return err
|
|
})
|
|
return err
|
|
}
|
|
|
|
func (p *CowyoData) encode() ([]byte, error) {
|
|
enc, err := json.Marshal(p)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return enc, nil
|
|
}
|
|
|
|
func (p *CowyoData) decode(data []byte) error {
|
|
err := json.Unmarshal(data, &p)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|