How to install and use godoc tool for golang programming ?

Problem

Sometimes you want to find some examples or specifications of a go module(package), you should use godoc, it is a tool to find the documents of a package quickly, but when you execute the godoc command in command line, you get some error message like this:

godoc fmt
command not found: godoc

Environments

The environments are as follows:

  • go version: go version go1.14.2 darwin/amd64
  • GOROOT: /usr/local/go
  • GOPATH: /Users/me/GoProjects/src
  • IDE: Intellij Idea Ultimate 2019.3 with go plugin

The godoc tool

GoDoc hosts documentation for Go packages on Bitbucket, GitHub, Launchpad and Google Project Hosting.

The source code for GoDoc is available on GitHub.

GoDoc displays documentation for GOOS=linux unless otherwise noted at the bottom of the documentation page.

Use godoc in your terminal

If you want to lookup some package’s documents in command line, you should install the go tool at first.

gotool

GoTools holds the source for various packages and tools that support the Go programming language.

Some of the tools, godoc and vet for example, are included in binary Go distributions.

Others, including the Go guru and the test coverage tool, can be fetched with go get.

Packages include a type-checker for Go and an implementation of the Static Single Assignment form (SSA) representation for Go programs.

Install godoc tool with golang tools

You should install the godoc command like this:

 go get -v  golang.org/x/tools/cmd/godoc
 
 go: found golang.org/x/tools/cmd/godoc in golang.org/x/tools v0.0.0-20200717024301-6ddee64345a6
go: downloading golang.org/x/net v0.0.0-20200625001655-4c5254603344
golang.org/x/tools/godoc/vfs/gatefs
golang.org/x/tools/godoc/vfs/mapfs
golang.org/x/tools/godoc/vfs/zipfs
golang.org/x/tools/godoc/static
golang.org/x/net/context/ctxhttp
golang.org/x/tools/playground
golang.org/x/tools/godoc/redirect
golang.org/x/tools/cmd/godoc

Use the godoc tool in command line

You can now use the godoc tool in command line to lookup documents of go packages:

go doc fmt.Println                     
package fmt // import "fmt"

func Println(a ...interface{}) (n int, err error)
    Println formats using the default formats for its operands and writes to
    standard output. Spaces are always added between operands and a newline is
    appended. It returns the number of bytes written and any write error
    encountered.

Use the godoc tool online

Instead of using the godoc commandline , you can also use it online in your web browser:

Navigate to : https://godoc.org/ , then you get this:

godoc1

search for package fmt, you get this, you can see that it more informative than the command line.

godoc2

References

You can view some references as follows: