github.com/v2pro/plz@v0.0.0-20221028024117-e5f9aec5b631/msgfmt/custom.go (about) 1 package msgfmt 2 3 import ( 4 "fmt" 5 "time" 6 "strings" 7 ) 8 9 var Formats = map[string]Format{ 10 "goTime": &GoTimeFormat{}, 11 } 12 13 type Format interface { 14 FormatterOf(targetKey string, formatArgs []string, sample []interface{}) (Formatter, error) 15 } 16 17 func newFuncFormatter(key string, funcName string, funcArgs []string, sample []interface{}) (ret Formatter, err error) { 18 defer func() { 19 recovered := recover() 20 if recovered != nil { 21 err = fmt.Errorf("newFormatter panic: %v", recovered) 22 } 23 }() 24 format := Formats[funcName] 25 if format == nil { 26 return nil, fmt.Errorf("format %s is not supported", funcName) 27 } 28 return format.FormatterOf(key, funcArgs, sample) 29 } 30 31 type GoTimeFormat struct { 32 } 33 34 func (format *GoTimeFormat) FormatterOf(targetKey string, formatArgs []string, sample []interface{}) (Formatter, error) { 35 if len(formatArgs) == 0 { 36 formatArgs = append(formatArgs, time.RFC3339) 37 } 38 for i := 0; i < len(sample); i+= 2{ 39 key := sample[i].(string) 40 if key == targetKey { 41 _, isTime := sample[i+1].(time.Time) 42 if !isTime { 43 return nil, fmt.Errorf("%s is not time.Time", targetKey) 44 } 45 layout := strings.TrimSpace(formatArgs[0]) 46 return &goTimeFormatter{ 47 idx: i+1, 48 layout: layout, 49 }, nil 50 } 51 } 52 return nil, fmt.Errorf("%s not found in properties", targetKey) 53 } 54 55 type goTimeFormatter struct { 56 idx int 57 layout string 58 } 59 60 func (formatter *goTimeFormatter) Format(space []byte, kv []interface{}) []byte { 61 return kv[formatter.idx].(time.Time).AppendFormat(space, formatter.layout) 62 }