togo/togo.go
John Olheiser e8a896fbac
Initial commit
Signed-off-by: jolheiser <john.olheiser@gmail.com>
2021-04-08 23:58:22 -05:00

90 lines
1.8 KiB
Go

package togo
import (
"fmt"
"reflect"
"strings"
"time"
"github.com/huandu/xstrings"
)
var SpecialCases = map[string]string{
"ip": "IP",
"dob": "DOB",
"id": "ID",
"uuid": "UUID",
"url": "URL",
"html": "HTML",
"json": "JSON",
"yaml": "YAML",
"toml": "TOML",
}
func ToGo(name string, raw map[string]interface{}) GoStruct {
s := []Struct{
{
Name: name,
Fields: make([]Field, 0),
},
}
for key, val := range raw {
keyName := xstrings.ToCamelCase(key)
if special, ok := SpecialCases[strings.ToLower(key)]; ok {
keyName = special
}
f := Field{
Name: keyName,
Tag: key,
}
switch v := val.(type) {
case map[string]interface{}:
// Nested struct
f.Type = keyName
gs := ToGo(keyName, v)
s = append(s, gs.Structs...)
case map[interface{}]interface{}:
// Nested struct
f.Type = keyName
m := make(map[string]interface{})
for kv, vv := range v {
m[kv.(string)] = vv
}
gs := ToGo(keyName, m)
s = append(s, gs.Structs...)
case string, time.Time:
f.Type = "string"
case int, int64:
f.Type = "int"
case float64:
f.Type = "float64"
case bool:
f.Type = "bool"
case []interface{}:
switch vv := v[0].(type) {
case map[string]interface{}:
// Nested []struct
f.Type = fmt.Sprintf("[]%s", keyName)
gs := ToGo(keyName, vv)
s = append(s, gs.Structs...)
case string:
f.Type = "[]string"
case int, int64:
f.Type = "[]int"
case float64:
f.Type = "[]float64"
case bool:
f.Type = "[]bool"
default:
f.Type = "interface{}"
f.Comment = fmt.Sprintf("%v", reflect.TypeOf(v[0]))
}
default:
f.Type = "interface{}"
f.Comment = fmt.Sprintf("%v", reflect.TypeOf(v))
}
s[0].Fields = append(s[0].Fields, f)
}
return GoStruct{Structs: s}
}