Skip to content

Instantly share code, notes, and snippets.

@LukaGiorgadze
Last active February 27, 2023 18:44
Show Gist options
  • Save LukaGiorgadze/570a89a5c3c6d006120da8c29f6684ee to your computer and use it in GitHub Desktop.
Save LukaGiorgadze/570a89a5c3c6d006120da8c29f6684ee to your computer and use it in GitHub Desktop.
Example demonstration of ast package that retrieves all structs from .go file. (Stackoverflow answer)
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
"log"
)
// GetStructNamesFromFile Example usage of Go's excellent ast package
// retrieves all struct names from the .go file
func GetStructNamesFromFile(filePath string) (structs []string, err error) {
data, err := ioutil.ReadFile(filePath)
if err != nil {
return
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "", string(data), 0)
if err != nil {
return
}
for _, decl := range f.Decls {
gen, ok := decl.(*ast.GenDecl)
if !ok || gen.Tok != token.TYPE {
continue
}
for _, spec := range gen.Specs {
ts, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
structs = append(structs, ts.Name.Name)
}
}
return
}
func main() {
entities, err := GetStructNamesFromFile("dir/filename.go")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v", entities)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment