utils/maps.go

40 lines
729 B
Go
Raw Normal View History

2023-10-02 23:42:16 +02:00
package utils
import (
"encoding/json"
"fmt"
"reflect"
"sort"
)
// GetAllStringKeysOfMap returns all keys of a map with string keys (sorted)
func GetAllStringKeysOfMap(in interface{}) []string {
v := reflect.ValueOf(in)
if v.Kind() != reflect.Map {
return []string{}
}
keyType := v.Type().Key()
if keyType.Kind() != reflect.String {
return []string{}
}
keys := make([]string, v.Len())
for i, key := range v.MapKeys() {
keys[i] = key.String()
}
sort.Strings(keys)
return keys
}
// PrettyPrint tries to print in as a pretty JSON
func PrettyPrint(in interface{}) {
result, err := json.MarshalIndent(in, "", " ")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(result))
}