Use go/parser to convert source code into an AST, go/ast to inspect or modify that tree, and go/printer to generate valid Go code from the result.
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"os"
)
func main() {
fset := token.NewFileSet()
astFile, err := parser.ParseFile(fset, "main.go", nil, parser.ParseComments)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
// Inspect or modify the AST
ast.Inspect(astFile, func(n ast.Node) bool {
if fn, ok := n.(*ast.FuncDecl); ok {
fmt.Println("Found function:", fn.Name.Name)
}
return true
})
// Print the modified AST back to code
if err := printer.Fprint(os.Stdout, fset, astFile); err != nil {
fmt.Fprintln(os.Stderr, err)
}
}