Created
June 27, 2020 23:58
-
-
Save xeoncross/cdb501a44eacda865b00b4806dcb318a to your computer and use it in GitHub Desktop.
Parsing Go source code using the Go AST. https://play.golang.org/p/DGsfPkmZXD3
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" | |
) | |
// https://pkg.go.dev/go/ast?tab=doc#Object.Type | |
func main() { | |
fset := token.NewFileSet() | |
src := `package foo | |
type User struct { | |
ID uint64 | |
Name string | |
URL string | |
Disabled bool | |
Age int | |
}` | |
f, err := parser.ParseFile(fset, "", src, 0) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
// Full tree | |
//ast.Fprint(os.Stdout, fset, f, func(name string, value reflect.Value) bool { return true }) | |
for _, decl := range f.Decls { | |
switch d := decl.(type) { | |
case *ast.GenDecl: | |
for _, spec := range d.Specs { | |
s, ok := spec.(*ast.TypeSpec) | |
if !ok { | |
continue | |
} | |
t, ok := s.Type.(*ast.StructType) | |
if !ok { | |
continue | |
} | |
fmt.Printf("type %s struct:\n", s.Name) | |
for _, f := range t.Fields.List { | |
// fmt.Printf("\tfield: %+v\n", f) | |
fieldType, ok := f.Type.(*ast.Ident) | |
if !ok { | |
continue | |
} | |
name := f.Names[0].Name | |
fmt.Printf("\t%s %s\n", name, fieldType.Name) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment