Skip to content

Go Tools

Openweb edited this page Sep 3, 2022 · 25 revisions

Packages

Go offers reuse through packages. The language provides workspace construct to compose large programs by composing it into packages. A package can be reused by using keyword import.

import

A go program may import parts of a package, single package or multiple packages. The imports may be grouped by introducing blank lines.. To avoid namespace confusion a go import may be renamed.

A blank import implements a compile-time mechanism where main program can import additional features by importing additional packages. eg:

import (
  "image"
  "image/jpeg"
  _ "image/png" // Registers PNG decoders. Similar to initCLI in this repo where we register extra functionlity.
)

Packages Best Practices

  1. Keep package name as short but not cryptic.
  2. Be descriptive and unambiguous where possible.
  3. Use singular forms. Notable exceptions: bytes, strings (to avoid conflict with go keywords)
  4. Avoid package name that have other connotations eg temp (temporary or temperature)
  5. Consider how package.Method describes a member.

The Go Tool

The Command go is a comprehensive package for downloading, querying, formatting, building, testing and installing packages of Go code.

This sections describes some of the following go tools commands, described in Chapter 10: Packages and Go Tool:

  • go build
  • go get
  • go doc
  • go list

Complete list of go tool commands are:

$ go
Go is a tool for managing Go source code.
...
The commands are:

	bug         start a bug report
	build       compile packages and dependencies
	clean       remove object files and cached files
	doc         show documentation for package or symbol
	env         print Go environment information
	fix         update packages to use new APIs
	fmt         gofmt (reformat) package sources
	generate    generate Go files by processing source
	get         add dependencies to current module and install them
	install     compile and install packages and dependencies
	list        list packages or modules
	mod         module maintenance
	run         compile and run Go program
	test        test packages
	tool        run specified go tool
	version     print Go version
	vet         report likely mistakes in packages

Environment go env

A go workspace is a hierarchical directory structure defined in environment variable $GOPATH. Three main directories are:

  • $GOPATH/src: Contains all programs source code. May be individual git repos.
  • $GOPATH/pkg: Packages installed in workspace. Downloaded by go get command.
  • $GOPATH/bin: Compiled output of go install or binaries built by go get command.

All go shell variables can be viewed by go env command:

# Few of go env variables.
$ go env
GOARCH="amd64"
GOCACHE="/Users/guest/Library/Caches/go-build"
GOMODCACHE="/Users/guest/gocode/pkg/mod"
GOOS="darwin"
GOPATH="/Users/guest/gocode"
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/Cellar/go/1.15.2/libexec"
...

$GOROOT is another important variable that specifies root of Go distribution. That lists all standard packages libraries.

Download packages go get

Use go get tool to download a single package or entire subtree or repository. Once it has downloaded the packages go get installs the libraries and commands.

$ go get github.com/golang/lint/golint # Downloads and installs `golint`.

It has builtin support for GitHub, BitBucket and Launchpad and can make request to version control systems. See go help importpath. To import unsupported hosts specify protocol in import path eg:

import "example.org/repo.git/foo/bar" // Imports "bar" which is a .git style

Managing Modules

A module is a collection of related Go packages that are versioned together as a single unit. The go modules are installed in $GOPATH/pkg/mod directory when we run go install or go test ./... commands. Some handy commands are (run these in top go module directory):

go mod init # Default
go mod init github.com/opendroid/the-gpl # Alternate way
go mod tidy # do before release
go mod vendor # Optional creates a vendor directory
go clean -modcache # Clean up packages cache
go mod graph # list all depenedancies

# Manually getting go modules:
go get github.com/stretchr/testify/assert
go get cloud.google.com/go/dialogflow/apiv2
go get google.golang.org/genproto/googleapis/cloud/dialogflow/v2
go get google.golang.org/api/option
go list -u -m all # List all major/minor upgrades available
go get -u ./... # Upgrade all modules

Documentation go doc

The go doc commands prints declarations and doc comments of specified entity. eg

# Print sort package documentation
$ go doc sort
package sort // import "sort"

Package sort provides primitives for sorting slices and user-defined
collections.

func Float64s(a []float64)
func Float64sAreSorted(a []float64) bool
func Ints(a []int)
...

# Print documentation for sort.Sort
$ go doc sort.Sort
package sort // import "sort"

func Sort(data Interface)
    Sort sorts data. It makes one call to data.Len to determine n, and
    O(n*log(n)) calls to data.Less and data.Swap. The sort is not guaranteed to
    be stable

The Go uses comment for documentation.

Go Comments

Go documentation comments are for package and exported entities. The doc comment are always complete sentences, and first sentence is summary of name being declared. A good documentation need not be verbose. Go favors brevity and simplicity.

Web Documentation pkgsite

The pkgsite tool (replacement of godoc) serves cross linked web pages. In addition to Go Doc Comments it uses Examples to illustrate uses.

# Install the package:
go install golang.org/x/pkgsite/cmd/pkgsite@latest
# runt he command
pkgsite -http=localhost:6060 #will start a documentation server on localhost.

Too see a package go to http://localhost:6060/github.com/opendroid/coding/go_pipelines

Note that godoc is deprecated.

Query Packages go list

The go list reports information about available packages. It lists packages present in the workspace.

$ go list github.com/opendroid/the-gpl # List packages in the-gpl
$ go list github.com/opendroid/the-gpl/... # List all packages in the-gpl
$ go list ...json... # List all packages that match json name
$ go list ... # All packages in go workspace

The command also provides metadata using -json flag.

$ go list -json

The command uses -f flag to customize input using text/template style template language.

$ go list -f '{{join .Deps "\n"}}' # Lists all dependancies line by line
$ go list -f '{{join .Imports "\n"}}' # Lists all imports line by line
$ go list -f '{{range $idx, $f :=  .Imports}} {{printf "%d: %s\n" $idx $f}}{{end}}'  # show imports as 0: .. 1: .. 2: ...

References