package util import ( "bytes" "fmt" "io" "time" "github.com/pkg/errors" "kpt.xdmy/pkg/log" ) func Bool() { } func Zero(b bool) int { if b { return 1 } return 0 } func ZeroStr(b bool, s string) string { if b { return s } return "" } func ParseDate(d string) (res time.Time, err error) { if len(d) == 8 { d = d[:4] + "-" + d[4:6] + "-" + d[6:] } res, err = time.ParseInLocation("2006-01-02", d, time.Local) if err != nil { err = errors.Wrapf(err, "util ParseDate %s", d) log.Print(err.Error()) } return } func ParseDateAndTime(d, t string) (res time.Time, e error) { if d == "00000000" { return time.Now(), nil } if len(d) == 8 { d = d[:4] + "-" + d[4:6] + "-" + d[6:] } if len(t) == 6 { t = t[:2] + ":" + t[2:4] + ":" + t[4:] } if t != "" { d = d + " " + t } if res, e = time.ParseInLocation("2006-01-02 15:04:05", d, time.Local); e != nil { e = errors.Wrapf(e, "util ParseDateAndTime %s %s", d, t) } return } func Unmarshal(p interface{}, res interface{}) (e error) { b := []byte{} switch p.(type) { case string: b = []byte(p.(string)) case []byte: b = p.([]byte) default: if b, e = json.Marshal(p); e != nil { return errors.Wrapf(e, "util Unmarshal") } } fmt.Println(string(b)) e = json.Unmarshal(b, res) // defer func(e error) { // if e != nil { // log.Error("json UnMarshal ", e) // } // }(e) return errors.Wrapf(e, "util Unmarshal") } func UnmarshalNoflag(p interface{}, res interface{}) (err error) { b := make([]byte, 0) switch p.(type) { case string: b = []byte(p.(string)) case []byte: b = p.([]byte) default: b, err = json.Marshal(p) if err != nil { return } } err = json.Unmarshal(b, res) return } func Marshal(p interface{}) (b []byte, err error) { // json.MarshalIndent(p, "", " ") if b, err = json.Marshal(p); err != nil { log.Error("json Marshal error:", err, p) } return } func JsonMarshal(p interface{}) (r io.Reader, err error) { if p == nil { return } var b []byte switch p.(type) { case string: b = []byte(p.(string)) case []byte: b = p.([]byte) default: b, err = json.Marshal(p) if err != nil { err = log.Error("failed to marshal", err, p) return } } r = bytes.NewBuffer(b) return } func NewMap(name string, value interface{}) map[string]interface{} { return map[string]interface{}{ name: value, } }