1 Star 1 Fork 0

titan-kit/titan

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
Clone or Download
value.go 2.25 KB
Copy Edit Raw Blame History
蝶衣人生 authored 2021-05-29 14:04 . first commit
package config
import (
"encoding/json"
"fmt"
"reflect"
"strconv"
"sync/atomic"
"time"
)
var (
_ Value = (*atomicValue)(nil)
_ Value = (*errValue)(nil)
)
// Value 是配置值接口.
type Value interface {
Bool() (bool, error)
Int() (int64, error)
Float() (float64, error)
String() (string, error)
Duration() (time.Duration, error)
Scan(interface{}) error
}
type atomicValue struct {
atomic.Value
}
func (v *atomicValue) Bool() (bool, error) {
switch val := v.Load().(type) {
case bool:
return val, nil
case int64, float64, string:
return strconv.ParseBool(fmt.Sprint(val))
}
return false, fmt.Errorf("type assert to %v failed", reflect.TypeOf(v.Load()))
}
func (v *atomicValue) Int() (int64, error) {
switch val := v.Load().(type) {
case int64:
return val, nil
case float64:
return int64(val), nil
case string:
return strconv.ParseInt(val, 10, 64)
}
return 0, fmt.Errorf("type assert to %v failed", reflect.TypeOf(v.Load()))
}
func (v *atomicValue) Float() (float64, error) {
switch val := v.Load().(type) {
case float64:
return val, nil
case int64:
return float64(val), nil
case string:
return strconv.ParseFloat(val, 10)
}
return 0.0, fmt.Errorf("type assert to %v failed", reflect.TypeOf(v.Load()))
}
func (v *atomicValue) String() (string, error) {
switch val := v.Load().(type) {
case string:
return val, nil
case bool, int64, float64:
return fmt.Sprint(val), nil
}
return "", fmt.Errorf("type assert to %v failed", reflect.TypeOf(v.Load()))
}
func (v *atomicValue) Duration() (time.Duration, error) {
val, err := v.Int()
if err != nil {
return 0, err
}
return time.Duration(val), nil
}
func (v *atomicValue) Scan(clazz interface{}) error {
val, err := v.String()
if err != nil {
return err
} else {
return json.Unmarshal([]byte(val), clazz)
}
}
type errValue struct {
err error
}
func (v errValue) Bool() (bool, error) { return false, v.err }
func (v errValue) Int() (int64, error) { return 0, v.err }
func (v errValue) Float() (float64, error) { return 0.0, v.err }
func (v errValue) Duration() (time.Duration, error) { return 0, v.err }
func (v errValue) String() (string, error) { return "", v.err }
func (v errValue) Scan(interface{}) error { return v.err }
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/titan-kit/titan.git
git@gitee.com:titan-kit/titan.git
titan-kit
titan
titan
v0.0.4

Search