// Package util ... // // Description : util ... // // Author : go_developer@163.com<白茶清欢> // // Date : 2023-04-04 16:09 package util import ( "bytes" "encoding/json" "fmt" "reflect" ) // console 终端数据输出的一些操作 // // Author : go_developer@163.com<白茶清欢> // // Date : 16:10 2023/4/4 type console struct { enable bool formatJson bool } // Enable 启用 // // Author : go_developer@163.com<白茶清欢> // // Date : 16:10 2023/4/4 func (c *console) Enable() { c.enable = true } // Disable 禁用 // // Author : go_developer@163.com<白茶清欢> // // Date : 16:11 2023/4/4 func (c *console) Disable() { c.enable = false } // FormatJson 是否格式化json // // Author : go_developer@163.com<白茶清欢> // // Date : 16:35 2023/4/4 func (c *console) FormatJson(format bool) { c.formatJson = format } // Output 禁用终端输出 // // Author : go_developer@163.com<白茶清欢> // // Date : 16:13 2023/4/4 func (c *console) Output(dataList ...interface{}) { if !c.enable { return } for _, item := range dataList { fmt.Println(c.getDataStr(item)) } } // getDataStr 数据转换为字符串 // // Author : go_developer@163.com<白茶清欢> // // Date : 16:14 2023/4/4 func (c *console) getDataStr(data interface{}) string { if nil == data { return "nil" } dataValue := reflect.ValueOf(data) dataType := reflect.TypeOf(data).Kind() if dataType == reflect.Ptr { dataValue = dataValue.Elem() } switch dataValue.Kind() { case reflect.Map: fallthrough case reflect.Slice: fallthrough case reflect.Array: fallthrough case reflect.Struct: byteData, _ := json.Marshal(data) if !c.formatJson { return string(byteData) } var out bytes.Buffer _ = json.Indent(&out, []byte(string(byteData)+"\n"), "", "\t") return string(out.Bytes()) case reflect.Func: return dataValue.String() default: return fmt.Sprintf("%v", data) } }