util/console.go

91 lines
1.6 KiB
Go

// Package util ...
//
// Description : util ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2023-04-04 16:09
package util
import (
"encoding/json"
"fmt"
"reflect"
)
// console 终端数据输出的一些操作
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:10 2023/4/4
type console struct {
enable 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
}
// Output 禁用终端输出
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:13 2023/4/4
func (c *console) Output(dataList ...interface{}) {
if !c.enable {
return
}
list := make([]interface{}, 0)
for _, item := range dataList {
list = append(list, c.getDataStr(item))
}
fmt.Println(list...)
}
// 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)
return string(byteData)
case reflect.Func:
return dataValue.String()
default:
return fmt.Sprintf("%v", data)
}
return ""
}