73 lines
1.6 KiB
Go
73 lines
1.6 KiB
Go
package utils
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"reflect"
|
|
)
|
|
|
|
func shortenString(s string, length int) string {
|
|
if len(s) > length {
|
|
return s[:length] + "..."
|
|
}
|
|
return s
|
|
}
|
|
|
|
func PrintStruct(receiver interface{}, prefix string, clipContent bool) {
|
|
// 获取结构体的反射值
|
|
val := reflect.ValueOf(receiver)
|
|
typ := val.Type()
|
|
|
|
log.Println("=========", val.Type().Name(), "=========")
|
|
|
|
// 检查是否是结构体
|
|
if val.Kind() != reflect.Struct {
|
|
log.Println("Error: Input is not a struct")
|
|
return
|
|
}
|
|
|
|
// 获取所有字段名的最大长度
|
|
maxFieldNameLen := 0
|
|
for i := 0; i < val.NumField(); i++ {
|
|
fieldName := typ.Field(i).Name
|
|
if len(fieldName) > maxFieldNameLen {
|
|
maxFieldNameLen = len(fieldName)
|
|
}
|
|
}
|
|
maxFieldNameLen += 1
|
|
|
|
// 打印字段名和字段值
|
|
for i := 0; i < val.NumField(); i++ {
|
|
field := typ.Field(i)
|
|
fieldName := field.Name
|
|
fieldValue := val.Field(i).Interface()
|
|
|
|
// 根据字段值的类型进行处理
|
|
var output string
|
|
switch v := fieldValue.(type) {
|
|
case string:
|
|
// 如果是字符串,调用 shortenString 函数缩短
|
|
if clipContent {
|
|
output = shortenString(v, 50)
|
|
} else {
|
|
output = v
|
|
}
|
|
case reflect.Value:
|
|
// 如果是反射值,递归调用 PrintStruct
|
|
if v.Kind() == reflect.Struct {
|
|
PrintStruct(v.Interface(), prefix+" ", clipContent)
|
|
continue
|
|
} else if v.Kind() == reflect.Array {
|
|
|
|
}
|
|
default:
|
|
// 如果是其他类型,直接输出
|
|
output = fmt.Sprintf("%v", v)
|
|
}
|
|
|
|
log.Printf("%s%-*s: [%s]", prefix, maxFieldNameLen, fieldName, output)
|
|
}
|
|
|
|
log.Println("================================")
|
|
}
|