如何在 golang 中获取 func 文档?

xsi*_*dll 3 go

如何在 go 代码中获取 func 描述?

// My very nice description
func myFunc() { ... }
Run Code Online (Sandbox Code Playgroud)

我想要My very nice description.

获取 func 的名称非常简单:

runtime.FuncForPC(reflect.ValueOf(myFunc).Pointer()).Name()
Run Code Online (Sandbox Code Playgroud)

文档有类似的东西吗?我可以解析原始的 go 文件。有什么捷径吗?

Cer*_*món 7

使用go/doc包从源代码中提取文档。


xsi*_*dll 6

以防万一有人需要代码,我会将其发布在这里。它可能仍然有点难看,但对于我的场景来说效果很好。您可以根据自己的需要进行调整。

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 ""
}
Run Code Online (Sandbox Code Playgroud)