How do you serve simple documentation for go programs using godoc as a webpage?

By default, godoc looks at the packages it finds via $GOROOT and $GOPATH. So given that your package is in Go workspace i.e in GOPATH, you can run

godoc fmt

which prints out documentation for fmt package.

If you want to generate docs for your package foo which is in $GOPATH/src/github.com/abcd/foo location, you should run

godoc github.com/abcd/foo

With the -http flag, godoc runs as a web server and presents the documentation as a web page.

godoc -http=:6060

Now navigate to http://localhost:6060/pkg/github.com/abcd/foo in browser to find docs as web page.

The -play flag can be used to enable playground in web interface.


godoc operates on package and type names, not filenames.

For example, to learn about io/ioutil package:

  • text output: godoc io/ioutil

  • just the ReadAll function: godoc io/ioutil ReadAll

  • in HTML: godoc -html io/ioutil ReadAll

  • in the browser:

    • godoc -http=:6060
    • click Packages and navigate from there
    • or go directly to http://localhost:6060/pkg/io/ioutil#ReadAll

To view documentation for your own code, it has to be included in your GOPATH.

Suppose your GOPATH includes $HOME/go/src, and the file you are interested in is $HOME/go/src/hey/world/doc.go, you would run:

godoc hey/world

...or start godoc in HTTP mode and browse to http://localhost:6060/pkg/hey/world


To show HTML doc generated for your own code

Step 1) At command line start up the document web server, that is:

C:\>godoc -http=:6060

Step 2) Open a browser and use an explicit url the folder your code is.

The URL structure comes from the folder names under your GOPATH.

For example:

If my GOPATH is c:\go and I have code in c:\go\src\myfolder\mysubfolder

The URL I would uses is http://localhost:6060/pkg/myfolder/mysubfolder and this would show an HTML page for the .go files in there

Also you can use URL http://localhost:6060/pkg/myfolder, which will have a link to mysubfolder

Notes:

  • I'm not sure how to see your local code at the the http://localhost:6060/pkg level, maybe you can't
  • It is possible to "specify additional paths" so I don't think it has to be the src folder, see https://blog.golang.org/godoc-documenting-go-code

Tags:

Go

Godoc