代码拉取完成,页面将自动刷新
package FlySettings
import (
"encoding/base64"
"errors"
"strings"
"gitee.com/flyiot/flylibs/FlyDatabase"
"gitee.com/flyiot/flylibs/FlyJSON"
jsoniter "github.com/json-iterator/go"
)
type FlySettings struct {
FlyDB FlyDatabase.FlyDatabaseInterface
Ready bool
API jsoniter.API
}
func NewFlySettings() *FlySettings {
s := FlySettings{}
return &s
}
// 获取串口配置名称
func (s *FlySettings) Open(FlyDB FlyDatabase.FlyDatabaseInterface) error {
s.Ready = false
s.API = FlyJSON.MinAPI()
s.FlyDB = FlyDB
_, err := s.FlyDB.GetDB().DB()
if err != nil {
return err
}
err = s.FlyDB.AddTable(&FlySettingsTable{})
if err != nil {
return err
}
s.Ready = true
return nil
}
func (s *FlySettings) Set(key string, value any) error {
if !s.Ready {
return errors.New("settings not ready")
}
b, err := s.API.Marshal(value)
if err != nil {
return err
}
var row FlySettingsTable
DB := s.FlyDB.GetDB()
DB.FirstOrCreate(&row, FlySettingsTable{Key: key})
row.Value = string(b)
res := DB.Save(row)
return res.Error
}
func (s *FlySettings) GetObj(key string, obj any) error {
val := s.Get(key)
err := val.LastError()
if err != nil {
return err
}
val.ToVal(obj)
return val.LastError()
}
func (s *FlySettings) Get(key string) jsoniter.Any {
if !s.Ready {
return s.API.Get([]byte(""))
}
str := ""
var row FlySettingsTable
DB := s.FlyDB.GetDB()
DB.First(&row, "key = ?", key)
if len(row.Value) > 0 {
str = row.Value
}
return s.API.Get([]byte(str))
}
func (s *FlySettings) GetString(key string, defaults string) string {
any := s.Get(key)
v := any.ToString()
if v == "" {
return defaults
}
if any.LastError() == nil {
return v
}
return defaults
}
func (s *FlySettings) GetInt(key string, defaults int) int {
any := s.Get(key)
v := any.ToInt()
if any.LastError() == nil {
return v
}
return defaults
}
func (s *FlySettings) GetInt64(key string, defaults int64) int64 {
any := s.Get(key)
v := any.ToInt64()
if any.LastError() == nil {
return v
}
return defaults
}
func (s *FlySettings) GetFloat64(key string, defaults float64) float64 {
any := s.Get(key)
v := any.ToFloat64()
if any.LastError() == nil {
return v
}
return defaults
}
func (s *FlySettings) GetBool(key string, defaults bool) bool {
any := s.Get(key)
v := any.ToString()
if any.LastError() == nil {
v = strings.ToLower(v)
v = strings.TrimSpace(v)
if v == "" || v == "0" || v == "false" || v == "f" || v == "null" || v == "nil" || v == "undefined" || v == "empty" || v == "{}" || v == "[]" || v == `""` || v == `''` {
return false
}
if len(v) > 0 {
return true
}
}
return defaults
}
func (s *FlySettings) SetByte(key string, value []byte) {
bstr := base64.StdEncoding.EncodeToString(value)
s.Set(key, bstr)
}
func (s *FlySettings) GetByte(key string) ([]byte, error) {
str := s.GetString(key, "")
return base64.StdEncoding.DecodeString(str)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。