package main import ( "go/ast" "go/parser" "go/token" "log" "path/filepath" ) type Visitor struct { fset *token.FileSet } func (v *Visitor) Visit(node ast.Node) ast.Visitor { switch node.(type) { //判断ast分类 case *ast.FuncDecl: demo := node.(*ast.FuncDecl) // 打印具体的注释 println(demo.Doc.List[0].Text) // 可以打印出ast结构 ast.Print(v.fset, node) } return v } func main() { fset := token.NewFileSet() path, _ := filepath.Abs("./demo.go") f, err := parser.ParseFile(fset, path, nil, parser.ParseComments) if err != nil { log.Println(err) return } ast.Walk(&Visitor{ fset: fset, }, f) }
demo.go 被分析文件
// file commment package main type Article struct{} // @GET("/get") func (a Article) Get() { } // @POST("/save") func (a Article) Save() { }
输出:
// @GET("/get")
// @POST("/save")
标签:node,注释,fset,ast,demo,golang,func,go From: https://www.cnblogs.com/itsuibi/p/16978790.html