Talk about godoc, go doc and pkgsite

Permalink to this article – https://ift.tt/OSaJdYV

Just like the Go built-in unit testing framework discussed in the previous article , Go, which not only pays attention to language features, but also does not forget to provide overall environment features for Go software projects, has defined how to write code documents through comments in the source code at the beginning of its birth. format , and provides tools to generate Go documentation in real time based on code comments and support documentation viewing.

Some early languages, such as C, C++, etc., need to use third-party tools (such as doxygen ) and the specific formats specified by these tools to write documents, lacking language-native document standards and tools, which brings difficulties to the collaboration between later developers. trouble.

Viewing documentation is one of the daily essential development activities for developers. The Go language has attached great importance to the construction of project documents since the day it was born. For this reason, Go provides a variety of rich document viewing tools for gophers. In addition to viewing the latest stable version of the documents online on the Go official website , Go also Provides developers with tools to view documents locally offline , such as: godoc , go doc and pkgsite . In this short article, let’s take a look at each of the three Go documentation viewing tools.

1. godoc

Many gophers who have been in contact with the Go language earlier know that the Go installation package has a native document viewing tool released together with go and gofmt: godoc . It’s also the first documentation viewer for Go !

Godoc is essentially a web service, which will establish a web-form Go documentation center locally offline, and provide document viewing services for locally installed go packages.

The document center service starts when we execute the following command:

 $godoc -http=localhost:8080

Enter http://localhost:8080 in the browser address bar to open the homepage of the Go Documentation Center. Godoc will display the directory structure under \$GOROOT by default:

We see that the menu at the top of the homepage is basically the same as the menu on the old official homepage of Go .

Click on Packages again and we will see that godoc will display the reference documentation page of the local package:

The Go package reference documentation page divides packages into several categories: Standard library, Third party and Other packages. The third party packages are the packages under the local \$GOPATH.

Find the standard library io package under Standard Library on the “Packages” page, and click to open the reference document page of the Go io package, as shown in the following figure:

In this way, we can view go module related documents in the form of web pages offline! Before Go 1.13 version , this is like setting up a mirror site of Go official website locally.

Moreover, godoc supports the -play command line option, which can start the playground function, and the example in the go document can also run like an online playground:

However, this function is not offline , and cannot be run with the local Go compiler and environment, and needs to be connected to the network.

Godoc also supports viewing historical versions of Go documents . This has been written before, and you can read it step by step.

Next, let’s talk about the status quo of the godoc tool! Unfortunately, since Go version 1.13 , godoc has lost its status as an official tool, and it is no longer released together with go and gofmt in the Go installation package! If you want to use godoc, you need to install it yourself using the following command:

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

With the release of Go’s new official website in 2019, the godoc-style web document viewing method has gradually been forgotten! godoc.org is also down.

At the end of 2021, the godoc tool is also marked as deprecated (although there are still several commits in the past two years), which marks the official exit of godoc from the stage of history!

Note: Nostalgic gophers have built an alternative to godoc.org: https://godocs.io, maintained by the Go community.

So, without godoc, how can we query go documents offline? Let’s talk about the command-line tool go doc for viewing go documents locally.

2. go doc

go doc is a command-line tool that comes with the Go language, which can be used to view the documentation of the locally installed Go package. Unlike godoc, go doc does not need to start the HTTP server, it can be used directly in the terminal:

Since go doc was added to the Go toolchain in Go 1.5 , it has become a go subcommand that Gophers must use every day, just like go get and go build.

When looking at the package documentation, the parameters accepted by go doc on the command line use the format of Go grammar, which makes the use of go doc almost “zero threshold”:

 go doc <pkg> go doc <sym>[.<methodOrField>] go doc [<pkg>.]<sym>[.<methodOrField>] go doc [<pkg>.][<sym>.]<methodOrField>

Let’s briefly introduce how to use go doc to view various package documents.

  • Check out the standard library documentation

We can execute the go doc command in any path to view the standard library documentation. Below are some examples of commands to view the documentation of different elements of the standard library.

View the standard library net/http package documentation:

 $go doc net/http或$go doc http

Check out the documentation for the Get function of the http package:

 $ go doc net/http.Get或$ go doc http.Get

View the documentation of the field Form in the structure type Requset in the http package:

 $go doc net/http.Request.Form或$go doc http.Request.Form
  • View current project documentation

In addition to looking at the standard library documentation, we are likely to look at the documentation of other packages in the current project when we are engaged in project development to determine how to use these packages. go doc can also easily view the documentation of the project in the current path. Let’s take the github.com/bigwhite/gocmpp project that has been downloaded locally (for example: ~/temp/gocmpp) as an example.

View the documentation of the package in the current path:

 $go doc package cmpp // import "github.com/bigwhite/gocmpp" const CmppActiveTestReqPktLen uint32 = 12 ... const CmppConnReqPktLen uint32 = 4 + 4 + 4 + 6 + 16 + 1 + 4 ... const Cmpp2DeliverReqPktMaxLen uint32 = 12 + 233 ... ... ...

Check out the documentation for the export element of the package at the current path:

 $go doc CmppActiveTestReqPktLen package cmpp // import "." const ( CmppActiveTestReqPktLen uint32 = 12 //12d, 0xc CmppActiveTestRspPktLen uint32 = 12 + 1 //13d, 0xd ) Packet length const for cmpp active test request and response packets.

We see that the first letter of the package export element (such as CmppActiveTestReqPktLen) is capitalized, go doc will not parse it into a package name, but will think it is an element in the current package.

Through the -u option, we can also view the documentation of the non-exported elements of the package under the current path:

 $go doc -u newPacketWriter package cmpp // import "github.com/bigwhite/gocmpp" func newPacketWriter(initSize uint32) *packetWriter

View the documentation for a package in a subpath of the current path:

 $go doc ./utils或$go doc utils package cmpputils // import "github.com/bigwhite/gocmpp/utils" var ErrInvalidUtf8Rune = errors.New("Not Invalid Utf8 runes") func GB18030ToUtf8(in string) (string, error) ... ...
  • View the documentation of the third-party module that the project depends on

Today, go modules are the standard pattern for Go dependency management. The go module that a project depends on will be cached in the go mod exclusive path, including different versions and its code. Therefore, at present, when go doc views the documentation of a third-party module that the project depends on, it will automatically find the module in the go mod cache and display its documentation, for example:

 $go doc github.com/lni/dragonboat/v3 package dragonboat // import "github.com/lni/dragonboat/v3" Package dragonboat is a multi-group Raft implementation. The NodeHost struct is the facade interface for all features provided by the dragonboat package. Each NodeHost instance usually runs on a separate host managing its CPU, storage and network resources. Each NodeHost can manage Raft nodes from many different Raft groups known as Raft clusters. Each Raft cluster is identified by its ClusterID and it usually consists of multiple nodes, each identified its NodeID value. Nodes from the same Raft cluster can be considered as replicas of the same data, they are suppose to be distributed on different NodeHost instances across the network, this brings fault tolerance to machine and network failures as application data stored in the Raft cluster will be available as long as the majority of its managing NodeHost instances (ie its underlying hosts) are available. ... ... const DragonboatMajor = 3 ... var ErrClosed = errors.New("dragonboat: closed") ... var ErrInvalidOperation = errors.New("invalid operation") ... var ErrBadKey = errors.New("bad key try again later") ... var ErrNoSnapshot = errors.New("no snapshot available") ... func IsTempError(err error) bool func WriteHealthMetrics(w io.Writer) type ClusterInfo struct{ ... } type GossipInfo struct{ ... } type INodeUser interface{ ... } type Membership struct{ ... } type NodeHost struct{ ... } func NewNodeHost(nhConfig config.NodeHostConfig) (*NodeHost, error) type NodeHostInfo struct{ ... } type NodeHostInfoOption struct{ ... } var DefaultNodeHostInfoOption NodeHostInfoOption type RequestResult struct{ ... } type RequestResultCode int type RequestState struct{ ... } type SnapshotOption struct{ ... } var DefaultSnapshotOption SnapshotOption type SysOpState struct{ ... } type Target = string

If the dependent module you want to view has not been obtained locally, go doc will prompt you to go get it first.

In the traditional gopath mode, go doc will automatically search for the corresponding package path under \$GOPATH. If the package exists, it can output the relevant documents of the package. Therefore, we can view the documentation of the third-party project package through go doc in any path:

 $export GO111MODULE=off $go doc github.com/bigwhite/gocmpp.CmppActiveTestReqPktLen package cmpp // import "github.com/bigwhite/gocmpp" const ( CmppActiveTestReqPktLen uint32 = 12 //12d, 0xc CmppActiveTestRspPktLen uint32 = 12 + 1 //13d, 0xd ) Packet length const for cmpp active test request and response packets.
  • view source code

If we want to view the source code of the package, we don’t need to switch the directory to the path where the package is located and open the source file to view through the editor. We can also view the complete source code of the package or the source code of an element of the package through go doc.

View the standard library package source code:

 $go doc -src fmt.Printf package fmt // import "fmt" // Printf formats according to a format specifier and writes to standard output. // It returns the number of bytes written and any write error encountered. func Printf(format string, a ...interface{}) (n int, err error) { return Fprintf(os.Stdout, format, a...) }

View the source code of the exported elements in the current path package:

 $go doc -src NewClient package cmpp // import "." // New establishes a new cmpp client. func NewClient(typ Type) *Client { return &Client{ typ: typ, } }

View the source code of unexported elements in the current path package:

 $go doc -u -src newPacketWriter package cmpp // import "github.com/bigwhite/gocmpp" func newPacketWriter(initSize uint32) *packetWriter { buf := make([]byte, 0, initSize) return &packetWriter{ wb: bytes.NewBuffer(buf), } }

View the source code of a function of a third-party package that the current project depends on:

 $go doc -src github.com/lni/dragonboat/v3 IsTempError package dragonboat // import "github.com/lni/dragonboat/v3" // IsTempError returns a boolean value indicating whether the specified error // is a temporary error that worth to be retried later with the exact same // input, potentially on a more suitable NodeHost instance. func IsTempError(err error) bool { return err == ErrSystemBusy || err == ErrClusterClosed || err == ErrClusterNotInitialized || err == ErrClusterNotReady || err == ErrTimeout || err == ErrClosed }

go doc is a native tool, and it is also very powerful, but go doc is a cli tool, which cannot satisfy everyone’s “taste”, so friends may ask: Is there an alternative tool for offline web document centers like godoc? Let’s talk about pkgsite next.

3. pkgsite

After Go officially launched the new package documentation site, there are indeed many improvements in the user experience, and many new functions have been added. The following is the presentation form of the io package under the new package documentation site:

The old version of Go’s official site matches godoc. Similarly, after launching the new version of the Go package documentation site , Go also open sourced its source code. This project is pkgsite . We can install pkgsite with the following command:

 $go install golang.org/x/pkgsite/cmd/pkgsite@latest

Like godoc, pkgsite supports local mode, that is, offline mode. We can execute the following command under a go module (here under the local path of gocmpp module):

 $pkgsite 2023/03/16 23:26:37 Info: go/packages.Load(["all"]) loaded 247 packages from . in 3.762976863s 2023/03/16 23:26:37 Info: Listening on addr http://localhost:8080

We see that pkgsite loaded all packages in the “all” scope as well as the packages of the current module. Open the browser and enter localhost:8080 to open the home page of the pkgsite service:

Note: View the meaning of all through go help packages

Search for the package you want, and after getting the list, open the details page of the package, the display form is exactly the same as the official pkg.go.dev.

However, currently there is a problem with pkgsite viewing standard library packages in local mode , and the page cannot be opened.

The overall feeling is that pkgsite mainly meets the online document viewing needs of the official site at present. The support for the local mode is not very good , and it is relatively obscure to use. There are also gopher complaints here, hoping to restore the godoc tool , but it is estimated that the Go official will definitely not Will agree, after all, I don’t want to maintain two sets of tools with different display styles. There may be improvements to pkgsite in the future, but it seems that the priority is not high at present.

4. Summary

In daily development work, we are always online, and the online documentation of pkg.go.dev can meet most of the needs.

If it is really offline, I personally recommend that you at least install godoc and pkgsite on your development machine. For gophers who are used to godoc, although godoc has been “obsolete”, the compatibility of Go’s annotation-based documents is good, and godoc can still meet the initial offline document viewing needs. If you already like the style of Go’s new site and depend on the new site’s functions, then pkgsite is also available. Supplemented by the go doc command-line tool, offline viewing of documents can also meet the needs of seven or eighty-eight.

Note: If you are using an IDE tool like goland, its built-in offline documentation function may meet your needs.

The Go community also has some third-party offline go documentation tools, such as the golds of brother tapir (go101), which is also good.


“Gopher Tribe” knowledge planet aims to create a boutique Go learning and advanced community! High-quality first release of Go technical articles, “three days” first reading right, analysis of the development status of Go language twice a year, fresh Gopher daily 1 hour in advance every day, online courses, technical columns, book content preview, must answer within six hours Guaranteed to meet all your needs about the Go language ecology! In 2023, the Gopher tribe will further focus on how to write elegant, authentic, readable, and testable Go code, pay attention to code quality and deeply understand Go core technology, and continue to strengthen interaction with star friends. Everyone is welcome to join!

img{512x368}

img{512x368}

img{512x368}

img{512x368}

The well-known cloud hosting service provider DigitalOcean released the latest hosting plan. The entry-level Droplet configuration is upgraded to: 1 core CPU, 1G memory, 25G high-speed SSD, and the price is 5$/month. Friends who need to use DigitalOcean can open this link address : https://ift.tt/NM9mieP to start your DO host road.

Gopher Daily (Gopher Daily News) archive repository – https://ift.tt/A0JYX8D

my contact information:

  • Weibo (temporarily unavailable): https://ift.tt/MYszQ8y
  • Weibo 2: https://ift.tt/YkK0Z7I
  • Blog: tonybai.com
  • github: https://ift.tt/pVSgJWa

Business cooperation methods: writing, publishing, training, online courses, partnerships, consulting, advertising cooperation.

© 2023, bigwhite . All rights reserved.

This article is transferred from https://tonybai.com/2023/03/20/godoc-vs-go-doc-vs-pkgsite/
This site is only for collection, and the copyright belongs to the original author.