Golang本地包Godoc使用指南

Golang本地包Godoc使用指南 你好, 我尝试为创建的本地包生成文档并访问它,但未能成功。

提前致谢, LP

8 回复

你执行了哪些具体命令?发生了什么?

更多关于Golang本地包Godoc使用指南的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


交换参数顺序,包名必须放在最后。

如果你的 $GOPATH/foo,并且在 /foo/src/bar 中有一些包,那么包名仅为 bar。请尝试 godoc calc

func main() {
    fmt.Println("hello world")
}

Luca_Paterlini:

2019/02/12 12:20:30 cannot find package “.” in: /src/calc

你确定你的 GOPATH/home/pater92/Documents/go_study/goRecipes/src/testing/testing8_1/ 吗?请在你调用 godoc 的同一个终端中执行 go env GOPATH

我执行了 godoc src/calc

godoc src/calc
2019/02/12 11:20:17 cannot find package "." in:
/src/calc

这是我的 gopath

echo $GOPATH
/home/pater92/Documents/go_study/goRecipes/src/testing/testing8_1/

这是包所在的路径

/home/pater92/Documents/go_study/goRecipes/src/testing/testing8_1/src/calc

同样的结果,godoc calc 2019/02/12 12:20:30 无法在以下路径找到包“.”: /src/calc

使用这个命令效果稍好一些,但示例文件仍然没有踪迹

/Documents/go_study/ goRecipes/src/testing/testing8_1/src/calc$ godoc . 包文档

package calc import “.”

Package calc implements sum and avg

函数

func Average(nums …int) float64

func Sum(nums …int) int

是的,这样更好,我已经更改了gopath,因为原来的路径中包含了一个空白字符

pater92@pater92-HP-Notebook:~/Documents/go_study/goRecipes/src/testing/testing8_1$ go doc calc
package calc // import "calc"

Package calc implements sum and avg

func Average(nums ...int) float64
func Sum(nums ...int) int
pater92@pater92-HP-Notebook:~/Documents/go_study/goRecipes/src/testing/testing8_1$ go doc calc -http=:3000
doc: invalid identifier "-http=:3000"
exit status 1

在第一个命令中没有显示示例文件的踪迹,第二个命令只是报错,我的目标是仅为该特定包运行godoc服务器。感谢您提供的任何进一步帮助。

要在本地为Go包生成并访问文档,可以使用godoc工具。以下是具体步骤和示例:

1. 安装godoc工具

如果尚未安装,使用以下命令安装:

go install golang.org/x/tools/cmd/godoc@latest

2. 设置Go模块(如适用)

确保你的包位于Go模块中。在包根目录运行:

go mod init yourmodule

3. 编写包代码并添加注释

示例包结构:

mylocalpkg/
  go.mod
  mypkg.go

mypkg.go中:

// Package mypkg demonstrates a local package.
package mypkg

import "fmt"

// Greet returns a greeting message.
// It takes a name string and returns a formatted greeting.
func Greet(name string) string {
    return fmt.Sprintf("Hello, %s!", name)
}

// Version indicates the current package version.
const Version = "1.0.0"

4. 启动本地godoc服务器

在终端运行:

godoc -http=:6060

5. 访问文档

打开浏览器访问:http://localhost:6060/pkg/yourmodule/mypkg/

如果包不在模块中,使用完整导入路径:http://localhost:6060/pkg/full/import/path/

6. 验证包可访问性

确保包在GOPATH或模块中。检查:

go list yourmodule/mypkg

如果使用GOPATH,包应位于$GOPATH/src/yourpackage

故障排除

  • 如果文档未显示,确认注释使用正确格式(如// FunctionName ...)。
  • 对于模块,确保go.mod中模块名称与导入路径匹配。
  • 重启godoc服务器后重试。

示例输出:在浏览器中,你将看到包mypkg的文档,列出Greet函数和Version常量及其注释。

回到顶部