package helper import ( "encoding/json" "fmt" "reflect" "strconv" ) type Raw struct { val interface{} } type argInt []int func NewRaw(val interface{}) *Raw { return &Raw{val: val} } //json解码 func (v *Raw) JSONDecode(val interface{}) error { return json.Unmarshal(v.val.([]byte), val) } //json加密 func (v *Raw) JSONEncode() ([]byte, error) { j, err := json.Marshal(v.val) if err == nil { return j, nil } return nil, err } func (a argInt) Get(i int, args ...int) (r int) { if i >= 0 && i < len(a) { r = a[i] } if len(args) > 0 { r = args[0] } return r } func (v *Raw) Result(args ...int) *Result { return NewResult(v.ToStr(args...)) } func (v *Raw) String(args ...int) (s string) { return v.ToStr(args...) } func (v *Raw) Str(args ...int) *Str { return NewStr(v.ToStr(args...)) } //是否为空 func (r *Raw) Empty() bool { if r.val == nil { return true } v := reflect.ValueOf(r.val) switch v.Kind() { case reflect.String, reflect.Array: return v.Len() == 0 case reflect.Map, reflect.Slice: return v.Len() == 0 || v.IsNil() case reflect.Bool: return !v.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return v.Uint() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 case reflect.Interface, reflect.Ptr: return v.IsNil() } return reflect.DeepEqual(r.val, reflect.Zero(v.Type()).Interface()) } func (v *Raw) ToStr(args ...int) (s string) { switch v := v.val.(type) { case bool: s = strconv.FormatBool(v) case float32: s = strconv.FormatFloat(float64(v), 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 32)) case float64: s = strconv.FormatFloat(v, 'f', argInt(args).Get(0, -1), argInt(args).Get(1, 64)) case int: s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10)) case int8: s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10)) case int16: s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10)) case int32: s = strconv.FormatInt(int64(v), argInt(args).Get(0, 10)) case int64: s = strconv.FormatInt(v, argInt(args).Get(0, 10)) case uint: s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10)) case uint8: s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10)) case uint16: s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10)) case uint32: s = strconv.FormatUint(uint64(v), argInt(args).Get(0, 10)) case uint64: s = strconv.FormatUint(v, argInt(args).Get(0, 10)) case string: s = v case []byte: s = string(v) default: s = fmt.Sprintf("%v", v) } return s }