Skip to content

Instantly share code, notes, and snippets.

@ncdc
Created November 9, 2016 20:50
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ncdc/fef1099f54a655f8fb11daf86f7868b8 to your computer and use it in GitHub Desktop.
Save ncdc/fef1099f54a655f8fb11daf86f7868b8 to your computer and use it in GitHub Desktop.
golang ast parsing to extract a variable's value
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
)
func main() {
// borrowed from https://github.com/lukehoban/go-outline/blob/master/main.go#L54-L107
fset := token.NewFileSet()
parserMode := parser.ParseComments
var fileAst *ast.File
var err error
fileAst, err = parser.ParseFile(fset, "group.go", nil, parserMode)
if err != nil {
panic(err)
}
for _, d := range fileAst.Decls {
switch decl := d.(type) {
case *ast.FuncDecl:
fmt.Println("Func")
case *ast.GenDecl:
for _, spec := range decl.Specs {
switch spec := spec.(type) {
case *ast.ImportSpec:
fmt.Println("Import", spec.Path.Value)
case *ast.TypeSpec:
fmt.Println("Type", spec.Name.String())
case *ast.ValueSpec:
for _, id := range spec.Names {
fmt.Printf("Var %s: %v", id.Name, id.Obj.Decl.(*ast.ValueSpec).Values[0].(*ast.BasicLit).Value)
}
default:
fmt.Printf("Unknown token type: %s\n", decl.Tok)
}
}
default:
fmt.Printf("Unknown declaration @\n", decl.Pos())
}
}
}
package main
const GroupName = "andy"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment