golang基础(2) - godoc的用法
golang golang
Lastmod: 2020-09-20

安装完成go后,在$GOROOT/bin/下目前会有三个文件:go, godoc和gofmt。go就不用说了,gofmt大部分人都熟悉,因为它解决了代码风格的问题,代码风格是code review中的一个大问题,减少了revie时很多鸡毛蒜皮类的争论,节省了时间。但是godoc,可能很多人就不太熟悉了,本文主要是对godoc的使用做简单介绍。

$GOROOT就是go的安装目录,linux下一般是/usr/local/go, mac os下使用brew一般是/usr/local/Cellar/go/版本/

基本用法

启动服务

godoc -http :6060

以上命令会在本地下生成当前系统安装的文档,类似于在本地启动了一个官方网站,不过里面的内容是基于当前安装的版本的。

除了有官方blog,官方包的文档以外,还有第三方库的文档,这里的第三方库指的是在$GOPATH/src下除了golang.org目录以外的所有库。

可能有人会问,你这么做有什么意义了,要查文档,直接网络搜索即可,甚至使用Dash这样的神器,不是更方便吗?那我只能说Too young to naive了。如果是一个团队,写了很多公司私有的公共组件,那么此时一个公共的文档库就极为重要了。而godoc就提供了这个功能。如果不用godoc,就需要单独写文档,写文档的工作量,地球人都知道,那不是一般的大。。。而且写完后,一般都没人看。。。

工程化的理念真的是贯穿于整个golang的。

godoc生成的文档有特定的格式,只要代码中的注释按照标准(标准很简单,下文有写),那么最后生成的文档格式是很易读的。想想看,直接在代码中写注释,修改代码的时候就修改注释,而文档了,自动生成,始终和代码/注释保持一致。这个可是解决了软件工程领域的一个大问题啊:文档及时性。

所以说,golang是一门现代化的语言,一点都不过。

好像有点扯多了,请原谅我,每次在看golang设计精巧的地方,都不得不拍案而起,不是golang功能、性能等方面多么牛逼,而是,它真的能解决工程中的问题!

开启搜索功能

没有搜索功能的网站是不完整的

生成索引文件:

godoc -v -index -write_index -index_files /path/to/生成的索引文件

启动带搜索功能的服务:

godoc -http :6060 -index -index_files /path/to/生成的索引文件

golang注释标准

golang官方没有一个特别标准的文档来说明注释标准,主要散落在3个地方:

个人觉得记住下面几句话, 大部分场景就够用了:

  • 每一个包需要有包级别的注释,类似于Package 包名 ...这种模式。如果包中有多个源文件,只需要任意一个源文件有包级别注释即可。
  • 结构体、函数和方法的注释类似于结构体名/函数名/方法名 ...这种模式
  • 不要尝试使用空格去格式化注释,对齐即可。godoc生成时会类似于gofmt对源代码做的一样,会自动转化格式。
  • 注释应该是完整的句子。

内容真的不多,我就汇总摘抄到这里吧: Every package should have a package comment. It should immediately precede the package statement in one of the files in the package. (It only needs to appear in one file.) It should begin with a single sentence that begins “Package packagename” and give a concise summary of the package functionality. This introductory sentence will be used in godoc’s list of all packages.

Subsequent sentences and/or paragraphs can give more details. Sentences should be properly punctuated.

// Package superman implements methods for saving the world.
//
// Experience has shown that a small number of procedures can prove
// helpful when attempting to save the world.
package superman

Nearly every top-level type, const, var and func should have a comment. A comment for bar should be in the form “bar floats on high o’er vales and hills.". The first letter of bar should not be capitalized unless it’s capitalized in the code.

// enterOrbit causes Superman to fly into low Earth orbit, a position
// that presents several possibilities for planet salvation.
func enterOrbit() os.Error {
  ...
}

Comments documenting declarations should be full sentences, even if that seems a little redundant. This approach makes them format well when extracted into godoc documentation. Comments should begin with the name of the thing being described and end in a period:

// Request represents a request to run a command.
type Request struct { ...

// Encode writes the JSON encoding of req to w.
func Encode(w io.Writer, req *Request) { ...

and so on

All top-level, exported names should have doc comments, as should non-trivial unexported type or function declarations. See https://golang.org/doc/effective_go.html#commentary for more information about commentary conventions.

Go provides C-style /* */ block comments and C++-style // line comments. Line comments are the norm; block comments appear mostly as package comments, but are useful within an expression or to disable large swaths of code.

The program—and web server—godoc processes Go source files to extract documentation about the contents of the package. Comments that appear before top-level declarations, with no intervening newlines, are extracted along with the declaration to serve as explanatory text for the item. The nature and style of these comments determines the quality of the documentation godoc produces.

Every package should have a package comment, a block comment preceding the package clause. For multi-file packages, the package comment only needs to be present in one file, and any one will do. The package comment should introduce the package and provide information relevant to the package as a whole. It will appear first on the godoc page and should set up the detailed documentation that follows.

/*
Package regexp implements a simple library for regular expressions.

The syntax of the regular expressions accepted is:

    regexp:
        concatenation { '|' concatenation }
    concatenation:
        { closure }
    closure:
        term [ '*' | '+' | '?' ]
    term:
        '^'
        '$'
        '.'
        character
        '[' [ '^' ] character-ranges ']'
        '(' regexp ')'
*/
package regexp

If the package is simple, the package comment can be brief.

// Package path implements utility routines for
// manipulating slash-separated filename paths.

Comments do not need extra formatting such as banners of stars. The generated output may not even be presented in a fixed-width font, so don’t depend on spacing for alignment—godoc, like gofmt, takes care of that. The comments are uninterpreted plain text, so HTML and other annotations such as this will reproduce verbatim and should not be used. One adjustment godoc does do is to display indented text in a fixed-width font, suitable for program snippets. The package comment for the fmt package uses this to good effect.

Depending on the context, godoc might not even reformat comments, so make sure they look good straight up: use correct spelling, punctuation, and sentence structure, fold long lines, and so on.

Inside a package, any comment immediately preceding a top-level declaration serves as a doc comment for that declaration. Every exported (capitalized) name in a program should have a doc comment.

Doc comments work best as complete sentences, which allow a wide variety of automated presentations. The first sentence should be a one-sentence summary that starts with the name being declared.

// Compile parses a regular expression and returns, if successful,
// a Regexp that can be used to match against text.
func Compile(str string) (*Regexp, error) {

If every doc comment begins with the name of the item it describes, you can use the doc subcommand of the go tool and run the output through grep. Imagine you couldn’t remember the name “Compile” but were looking for the parsing function for regular expressions, so you ran the command,

$ go doc -all regexp | grep -i parse

If all the doc comments in the package began, “This function…", grep wouldn’t help you remember the name. But because the package starts each doc comment with the name, you’d see something like this, which recalls the word you’re looking for.

$ go doc -all regexp | grep -i parse
    Compile parses a regular expression and returns, if successful, a Regexp
    MustCompile is like Compile but panics if the expression cannot be parsed.
    parsed. It simplifies safe initialization of global variables holding
$

Go’s declaration syntax allows grouping of declarations. A single doc comment can introduce a group of related constants or variables. Since the whole declaration is presented, such a comment can often be perfunctory.

// Error codes returned by failures to parse an expression.
var (
    ErrInternal      = errors.New("regexp: internal error")
    ErrUnmatchedLpar = errors.New("regexp: unmatched '('")
    ErrUnmatchedRpar = errors.New("regexp: unmatched ')'")
    ...
)

Grouping can also indicate relationships between items, such as the fact that a set of variables is protected by a mutex.

var (
    countLock   sync.Mutex
    inputCount  uint32
    outputCount uint32
    errorCount  uint32
)