Skip to content

Instantly share code, notes, and snippets.

@csthompson
Created September 18, 2020 03:41
Show Gist options
  • Save csthompson/ba83c323943f1ca72b96c642e9622f9b to your computer and use it in GitHub Desktop.
Save csthompson/ba83c323943f1ca72b96c642e9622f9b to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
)
func main() {
//Create a new token set for the file
fset := token.NewFileSet()
//Parse the file and create an AST
file, err := parser.ParseFile(fset, "../nats_publisher/main.go", nil, parser.ParseComments)
if err != nil {
panic(err)
}
//Create a CommentMap and extract all comments out of the file
cmap := ast.NewCommentMap(fset, file, file.Comments)
ast.Inspect(file, func(n ast.Node) bool {
//Look for all stand-alone expressions
_, ok := n.(*ast.ExprStmt)
if ok {
//Get the statement from the standalone expression (x) and attempt to cast to a function call
funcCall, ok := n.(*ast.ExprStmt).X.(*ast.CallExpr)
if ok {
//Check if it is a selector expression
mthd, ok := funcCall.Fun.(*ast.SelectorExpr)
if ok {
//Retrieve the identifier (the left side of the . in a selector expression)
_, ok = mthd.X.(*ast.Ident)
if ok {
//If method matches and the identifier is "ec" (encoded nats connection), extract values
if mthd.Sel.Name == "Publish" && mthd.X.(*ast.Ident).Name == "ec" {
fmt.Printf("Topic: %s \n", funcCall.Args[0].(*ast.BasicLit).Value)
if _, ok := cmap[n]; ok {
if len(cmap[n]) > 0 {
fmt.Println(cmap[n][0].Text())
}
}
}
}
}
}
}
return true
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment