golang 解析注释的方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package data

type U interface {
	A(i int) error
}

// 这个是实现类
// hello world
/*
sdfjljfalsjfa
*/
// X impl  xxxx
type X struct {
}

// a func
func (a X) A(u int) error {
	return nil
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main

//import "fmt"
import (
	"encoding/json"
	"fmt"

	aster "github.com/szyhf/go-aster"
)

func main() {
	goDir := "./data"

	pkgsTyp, err := aster.ParseDir(goDir, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	// simple display the result
	fs := pkgsTyp[0].Structs[0]
	fmt.Println(fs.Name, fs.Docs)
	//if len(fs) == 0 {
	var s, _ = json.MarshalIndent(fs, "", "\t")
	fmt.Println(string(s))
	//	return
	//}
	//var x = fs[0]
	//fmt.Println(x.Name)
	//fmt.Println(x.Params)
	//fmt.Println(x.Results)
	//fmt.Println(x.)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
{                                                               
        "Name": "X",                                            
        "Methods": [                                            
                {                                               
                        "Name": "A",                            
                        "Params": [                             
                                {                               
                                        "Name": "u",            
                                        "Type": {               
                                                "Name": "int",  
                                                "Kind": 1       
                                        }                       
                                }                               
                        ],                                      
                        "Results": [                            
                                {                               
                                        "Type": {               
                                                "Name": "error",
                                                "Kind": 1       
                                        }                       
                                }                               
                        ],                                      
                        "Receiver": {
                                "Name": "a",
                                "Type": {
                                        "Name": "X",
                                        "Kind": 1
                                }
                        }
                }
        ],
        "Docs": [
                "// 这个是实现类",
                "// hello world",
                "/*\nsdfjljfalsjfa\n*/",
                "// X impl  xxxx"
        ]
}

使用到的类库总结

参考 aster

参考 aster项目