fix: support output map[any]any type to console #81

This commit is contained in:
Lykin 2023-11-21 20:06:28 +08:00
parent 4ffbdbd39a
commit bfb5407030
2 changed files with 34 additions and 10 deletions

View File

@ -54,7 +54,7 @@ func (c *cliService) runCommand(server, data string) {
} }
} }
c.echo(server, strutil.AnyToString(result), true) c.echo(server, strutil.AnyToString(result, "", 0), true)
} else { } else {
c.echoError(server, err.Error()) c.echoError(server, err.Error())
} }

View File

@ -6,7 +6,7 @@ import (
sliceutil "tinyrdm/backend/utils/slice" sliceutil "tinyrdm/backend/utils/slice"
) )
func AnyToString(value interface{}) (s string) { func AnyToString(value interface{}, prefix string, layer int) (s string) {
if value == nil { if value == nil {
return return
} }
@ -49,7 +49,11 @@ func AnyToString(value interface{}) (s string) {
it := value.(uint64) it := value.(uint64)
s = strconv.FormatUint(it, 10) s = strconv.FormatUint(it, 10)
case string: case string:
if layer > 0 {
s = "\"" + value.(string) + "\""
} else {
s = value.(string) s = value.(string)
}
case bool: case bool:
val, _ := value.(bool) val, _ := value.(bool)
if val { if val {
@ -58,24 +62,44 @@ func AnyToString(value interface{}) (s string) {
s = "False" s = "False"
} }
case []byte: case []byte:
s = string(value.([]byte)) s = prefix + string(value.([]byte))
case []string: case []string:
ss := value.([]string) ss := value.([]string)
anyStr := sliceutil.Map(ss, func(i int) string { anyStr := sliceutil.Map(ss, func(i int) string {
str := AnyToString(ss[i]) str := AnyToString(ss[i], prefix, layer+1)
return strconv.Itoa(i+1) + ") \"" + str + "\"" return prefix + strconv.Itoa(i+1) + ") " + str
}) })
s = sliceutil.JoinString(anyStr, "\r\n") s = prefix + sliceutil.JoinString(anyStr, "\r\n")
case []any: case []any:
as := value.([]any) as := value.([]any)
anyItems := sliceutil.Map(as, func(i int) string { anyItems := sliceutil.Map(as, func(i int) string {
str := AnyToString(as[i]) str := AnyToString(as[i], prefix, layer+1)
return strconv.Itoa(i+1) + ") \"" + str + "\"" return prefix + strconv.Itoa(i+1) + ") " + str
}) })
s = sliceutil.JoinString(anyItems, "\r\n") s = sliceutil.JoinString(anyItems, "\r\n")
case map[any]any:
am := value.(map[any]any)
var items []string
index := 0
for k, v := range am {
kk := prefix + strconv.Itoa(index+1) + ") " + AnyToString(k, prefix, layer+1)
vv := prefix + strconv.Itoa(index+2) + ") " + AnyToString(v, "\t", layer+1)
if layer > 0 {
indent := layer
if index == 0 {
indent -= 1
}
for i := 0; i < indent; i++ {
vv = " " + vv
}
}
index += 2
items = append(items, kk, vv)
}
s = sliceutil.JoinString(items, "\r\n")
default: default:
b, _ := json.Marshal(value) b, _ := json.Marshal(value)
s = string(b) s = prefix + string(b)
} }
return return