From dc3c5d1068ce59bdb2fb4f43d5eb9a77b7b006a2 Mon Sep 17 00:00:00 2001 From: Nathan Coad Date: Tue, 16 Jan 2024 17:18:46 +1100 Subject: [PATCH] test new PrintStructContents --- utils/structOperations.go | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/utils/structOperations.go b/utils/structOperations.go index e756fe0..1b18913 100644 --- a/utils/structOperations.go +++ b/utils/structOperations.go @@ -2,11 +2,12 @@ package utils import ( "fmt" - "log" "reflect" "strings" + "time" ) +/* func PrintStructContents(s interface{}, indentLevel int) string { var result strings.Builder @@ -47,6 +48,42 @@ func PrintStructContents(s interface{}, indentLevel int) string { return result.String() } +*/ + +func PrintStructContents(s interface{}, indentLevel int) string { + var result strings.Builder + + val := reflect.ValueOf(s) + + if val.Kind() == reflect.Ptr { + val = val.Elem() + } + + typ := val.Type() + + for i := 0; i < val.NumField(); i++ { + field := val.Field(i) + fieldType := typ.Field(i) + + indent := strings.Repeat("\t", indentLevel) + result.WriteString(fmt.Sprintf("%s%s: ", indent, fieldType.Name)) + + switch field.Kind() { + case reflect.Struct: + if fieldType.Type == reflect.TypeOf(time.Time{}) { + // Handle time.Time field + result.WriteString(fmt.Sprintf("%v\n", field.Interface().(time.Time).Format("2006-01-02 15:04:05"))) + } else { + result.WriteString("\n") + result.WriteString(PrintStructContents(field.Interface(), indentLevel+1)) + } + default: + result.WriteString(fmt.Sprintf("%v\n", field.Interface())) + } + } + + return result.String() +} type Identifiable interface { GetId() int