Created
November 9, 2016 20:50
-
-
Save ncdc/fef1099f54a655f8fb11daf86f7868b8 to your computer and use it in GitHub Desktop.
golang ast parsing to extract a variable's value
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" | |
) | |
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()) | |
} | |
} | |
} |
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 | |
const GroupName = "andy" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment