boltbrowser/util/bolt_helpers.go

47 lines
834 B
Go
Raw Normal View History

2022-04-14 16:32:39 +00:00
package util
import (
"fmt"
"os"
bolt "go.etcd.io/bbolt"
)
func ToJsonString(b *bolt.Bucket) string {
ret := "{"
b.ForEach(func(k, v []byte) error {
ret = fmt.Sprintf("%s\"%s\":", ret, string(k))
if v == nil {
ret = fmt.Sprintf("%s%s,", ret, ToJsonString(b.Bucket(k)))
} else {
ret = fmt.Sprintf("%s\"%s\",", ret, string(v))
}
return nil
})
ret = fmt.Sprintf("%s}", ret[:len(ret)-1])
return ret
}
func LogToFile(s string) error {
return WriteToFile("bolt-log", s+"\n", os.O_RDWR|os.O_APPEND)
}
func WriteToFile(fn, s string, mode int) error {
var f *os.File
var err error
if f == nil {
f, err = os.OpenFile(fn, mode, 0660)
}
defer f.Close()
if err != nil {
return err
}
if _, err = f.WriteString(s); err != nil {
return err
}
if err = f.Sync(); err != nil {
return err
}
return nil
}