package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
)
func main() {
// src is the input for which we want to print the AST.
src := `
// @router /login [post]
// @router2 /login2 [post]
package main
func main() {
println("Hello, World!")
}
`
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, "", src, parser.ParseComments)
if err != nil {
panic(err)
}
for _, comment := range f.Comments {
fmt.Println(comment.Text())
}
// Print the AST.
ast.Print(fset, f)
}
运行结果如下:
@router /login [post]
@router2 /login2 [post]
0 *ast.File {
1 . Doc: *ast.CommentGroup {
2 . . List: []*ast.Comment (len = 2) {
3 . . . 0: *ast.Comment {
4 . . . . Slash: 2:1
5 . . . . Text: "// @router /login [post]"
6 . . . }
7 . . . 1: *ast.Comment {
8 . . . . Slash: 3:1
9 . . . . Text: "// @router2 /login2 [post]"
10 . . . }
11 . . }
12 . }
13 . Package: 4:1
14 . Name: *ast.Ident {
15 . . NamePos: 4:9
16 . . Name: "main"
17 . }
18 . Decls: []ast.Decl (len = 1) {
19 . . 0: *ast.FuncDecl {
20 . . . Name: *ast.Ident {
21 . . . . NamePos: 5:6
22 . . . . Name: "main"
23 . . . . Obj: *ast.Object {
24 . . . . . Kind: func
25 . . . . . Name: "main"
26 . . . . . Decl: *(obj @ 19)
27 . . . . }
28 . . . }
29 . . . Type: *ast.FuncType {
30 . . . . Func: 5:1
31 . . . . Params: *ast.FieldList {
32 . . . . . Opening: 5:10
33 . . . . . Closing: 5:11
34 . . . . }
35 . . . }
36 . . . Body: *ast.BlockStmt {
37 . . . . Lbrace: 5:13
38 . . . . List: []ast.Stmt (len = 1) {
39 . . . . . 0: *ast.ExprStmt {
40 . . . . . . X: *ast.CallExpr {
41 . . . . . . . Fun: *ast.Ident {
42 . . . . . . . . NamePos: 6:2
43 . . . . . . . . Name: "println"
44 . . . . . . . }
45 . . . . . . . Lparen: 6:9
46 . . . . . . . Args: []ast.Expr (len = 1) {
47 . . . . . . . . 0: *ast.BasicLit {
48 . . . . . . . . . ValuePos: 6:10
49 . . . . . . . . . Kind: STRING
50 . . . . . . . . . Value: "\"Hello, World!\""
51 . . . . . . . . }
52 . . . . . . . }
53 . . . . . . . Ellipsis: -
54 . . . . . . . Rparen: 6:25
55 . . . . . . }
56 . . . . . }
57 . . . . }
58 . . . . Rbrace: 7:1
59 . . . }
60 . . }
61 . }
62 . Scope: *ast.Scope {
63 . . Objects: map[string]*ast.Object (len = 1) {
64 . . . "main": *(obj @ 23)
65 . . }
66 . }
67 . Unresolved: []*ast.Ident (len = 1) {
68 . . 0: *(obj @ 41)
69 . }
70 . Comments: []*ast.CommentGroup (len = 1) {
71 . . 0: *(obj @ 1)
72 . }
73 }