Created
December 1, 2020 06:19
-
-
Save crhntr/20d6d609c7decef41af7fd0a5aa10f64 to your computer and use it in GitHub Desktop.
This script generates Javascript classes for go structs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"go/ast" | |
"go/parser" | |
"go/token" | |
"log" | |
"reflect" | |
"strings" | |
) | |
func main() { | |
var fileSet token.FileSet | |
packages, err := parser.ParseDir(&fileSet, "./", nil, parser.AllErrors) | |
if err != nil { | |
log.Println(err) | |
} | |
for _, pkg := range packages { | |
for _, file := range pkg.Files { | |
for _, decl := range file.Decls { | |
genDecl, ok := decl.(*ast.GenDecl) | |
if !ok { | |
continue | |
} | |
for _, spec := range genDecl.Specs { | |
typeSpec, ok := spec.(*ast.TypeSpec) | |
if !ok || !typeSpec.Name.IsExported() { | |
continue | |
} | |
structureSpec, ok := typeSpec.Type.(*ast.StructType) | |
if !ok { | |
continue | |
} | |
fmt.Printf("class %s {\n", typeSpec.Name) | |
for _, field := range structureSpec.Fields.List { | |
tpStr := typeString(field.Type) | |
if field.Tag == nil || len(field.Tag.Value) < 2{ | |
for _, name := range field.Names { | |
fmt.Printf("\t%s: %s\n", name, tpStr) | |
} | |
continue | |
} | |
tag := reflect.StructTag(field.Tag.Value[1:len(field.Tag.Value)]) | |
jsonTag, ok := tag.Lookup("json") | |
if !ok { | |
for _, name := range field.Names { | |
fmt.Printf("\t%s: %s\n", name, tpStr) | |
} | |
continue | |
} | |
jsonTag = strings.TrimSpace(strings.Split(jsonTag, ",")[0]) | |
fmt.Printf("\t%s: %s\n", jsonTag, tpStr) | |
} | |
fmt.Println("}") | |
} | |
} | |
} | |
} | |
} | |
func typeString(node ast.Expr) string { | |
switch nd := node.(type) { | |
case *ast.SelectorExpr: | |
ident, ok := nd.X.(*ast.Ident) | |
if !ok { | |
return "undefined" | |
} | |
switch nd.Sel.Name { | |
case "Time": | |
switch ident.Name { | |
case "time": | |
return "String" | |
} | |
case "ObjectID": | |
switch ident.Name { | |
case "primitive": | |
return "String" | |
} | |
} | |
case *ast.Ident: | |
switch nd.Name { | |
case "int", "float64": | |
return "Number" | |
case "bool": | |
return "Boolean" | |
case "string": | |
return "String" | |
} | |
return nd.Name | |
case *ast.ArrayType: | |
return typeString(nd.Elt) + "[]" | |
} | |
return "undefined" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment