2 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超9個(gè)贊
使用go/doc包從源代碼中提取文檔。
以防萬一有人需要代碼,我會(huì)把它貼在這里。它可能仍然有點(diǎn)難看,但適合我的場景。您可以根據(jù)自己的需要進(jìn)行調(diào)整。
package funcreader
import (
? ? "go/ast"
? ? "go/doc"
? ? "go/parser"
? ? "go/token"
? ? "path/filepath"
? ? "reflect"
? ? "runtime"
? ? "strings"
)
// Get the name and path of a func
func FuncPathAndName(f interface{}) string {
? ? return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
}
// Get the name of a func (with package path)
func FuncName(f interface{}) string {
? ? splitFuncName := strings.Split(FuncPathAndName(f), ".")
? ? return splitFuncName[len(splitFuncName)-1]
}
// Get description of a func
func FuncDescription(f interface{}) string {
? ? fileName, _ := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).FileLine(0)
? ? funcName := FuncName(f)
? ? fset := token.NewFileSet()
? ? // Parse src
? ? parsedAst, err := parser.ParseFile(fset, fileName, nil, parser.ParseComments)
? ? if err != nil {
? ? ? ? log.Fatal(err)
? ? ? ? return ""
? ? }
? ? pkg := &ast.Package{
? ? ? ? Name:? "Any",
? ? ? ? Files: make(map[string]*ast.File),
? ? }
? ? pkg.Files[fileName] = parsedAst
? ? importPath, _ := filepath.Abs("/")
? ? myDoc := doc.New(pkg, importPath, doc.AllDecls)
? ? for _, theFunc := range myDoc.Funcs {
? ? ? ? if theFunc.Name == funcName {
? ? ? ? ? ? return theFunc.Doc
? ? ? ? }
? ? }
? ? return ""
}
- 2 回答
- 0 關(guān)注
- 202 瀏覽
添加回答
舉報(bào)