Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created June 27, 2020 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeoncross/cdb501a44eacda865b00b4806dcb318a to your computer and use it in GitHub Desktop.
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
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