Go CLI
Introduction
The Go Command Line Interface (CLI) is a powerful set of tools that comes bundled with the Go programming language. These command-line utilities help you manage Go projects, build executables, test your code, and perform various other essential development tasks. As a beginner, understanding the Go CLI is crucial as it forms the foundation of your Go development workflow.
The Go CLI follows Go's philosophy of simplicity and effectiveness. With just a handful of commands, you can accomplish most of the tasks needed during Go development. In this guide, we'll explore the most important Go CLI commands, their usage, and provide practical examples to help you become comfortable using them in your projects.
Getting Started with Go CLI
Checking Your Go Installation
Before diving into the various CLI commands, let's verify that Go is properly installed on your system.
go version
Output:
go version go1.21.1 darwin/amd64
The output shows the installed Go version and your system architecture. If you see something similar, your Go installation is working correctly!
Getting Help
The Go CLI includes built-in help that provides information about available commands and their usage.
go help
Output:
Go is a tool for managing Go source code.
Usage:
go <command> [arguments]
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
work workspace 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
Use "go help <command>" for more information about a command.
For detailed help on a specific command:
go help <command>
For example:
go help build
Essential Go CLI Commands
1. go run
- Compile and Run Go Programs
The go run
command is perfect for quick testing during development. It compiles and runs your Go program in one step, without creating a permanent executable.
go run main.go
Let's see a practical example:
// main.go
package main
import "fmt"
func main() {
fmt.Println("Hello, Go CLI!")
}
Running this file:
go run main.go
Output:
Hello, Go CLI!
You can also run multiple files:
go run file1.go file2.go file3.go
Or run all files in the current package:
go run .
2. go build
- Compile Go Programs
The go build
command compiles your Go code into an executable file.
go build main.go
This will create an executable named after your file (main
or main.exe
on Windows). You can then run it directly:
./main
Output:
Hello, Go CLI!
To specify a custom output name:
go build -o myapp main.go
Building an entire package:
go build .
Building with optimizations for production:
go build -ldflags="-s -w" main.go
3. go install
- Compile and Install Go Programs
The go install
command compiles and installs packages to the Go bin directory, making them available system-wide.
go install github.com/username/project@latest
This will install the latest version of the specified package. The executable will be placed in $GOPATH/bin
or $GOBIN
if set.
4. go get
- Download and Install Packages
The go get
command downloads and installs packages and their dependencies.
go get github.com/gorilla/mux
In Go modules mode (Go 1.16+), it updates your go.mod
file and downloads the dependency:
go get -u github.com/gorilla/mux
The -u
flag updates the package to the latest version.
5. go mod
- Manage Modules
Go modules provide dependency management for Go projects. Here are some common go mod
commands:
Initialize a new module:
go mod init github.com/username/project
Output:
go: creating new go.mod: module github.com/username/project
This creates a go.mod
file:
module github.com/username/project
go 1.21
Tidy up the module's dependencies:
go mod tidy
This command adds missing dependencies and removes unused ones.
View the module's dependencies:
go mod graph
6. go test
- Test Your Code
Go has built-in testing support through the go test
command.
Consider this simple function and its test:
// math.go
package math
func Add(a, b int) int {
return a + b
}
// math_test.go
package math
import "testing"
func TestAdd(t *testing.T) {
got := Add(2, 3)
want := 5
if got != want {
t.Errorf("Add(2, 3) = %d; want %d", got, want)
}
}
Run the test:
go test
Output:
PASS
ok github.com/username/project/math 0.007s
For verbose output:
go test -v
Output:
=== RUN TestAdd
--- PASS: TestAdd (0.00s)
PASS
ok github.com/username/project/math 0.008s
Run tests with code coverage:
go test -cover
Output:
PASS
coverage: 100.0% of statements
ok github.com/username/project/math 0.007s
7. go fmt
- Format Your Code
Go has a standard code formatting style, and the go fmt
command ensures your code adheres to it.
go fmt main.go
Format all files in a package:
go fmt ./...
8. go vet
- Find Suspicious Code
The go vet
command checks your code for common mistakes and suspicious constructs.
go vet main.go
Examine all packages:
go vet ./...
Working with Go Workspaces
Go 1.18 introduced the workspace mode, which enables working with multiple modules simultaneously.
Create a workspace:
mkdir myworkspace
cd myworkspace
go work init
Add modules to the workspace:
go work use ./module1
go work use ./module2
Common Go CLI Workflows
Let's explore some common workflows that combine multiple Go CLI commands:
Setting Up a New Project
# Create a new directory
mkdir myproject
cd myproject
# Initialize a new module
go mod init github.com/username/myproject
# Create a simple main.go file
echo 'package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}' > main.go
# Run the program
go run main.go
# Add a dependency
go get github.com/gorilla/mux
# Tidy up dependencies
go mod tidy
Development Cycle
# Edit files
vim main.go
# Format code
go fmt ./...
# Check for issues
go vet ./...
# Run tests
go test ./...
# Build and run
go build -o myapp
./myapp
Environment Variables
The Go CLI uses several environment variables that control its behavior:
go env
Output (sample):
GO111MODULE="on"
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/username/Library/Caches/go-build"
GOENV="/Users/username/Library/Application Support/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOINSECURE=""
GOMODCACHE="/Users/username/go/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="darwin"
GOPATH="/Users/username/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
GOVCS=""
GOVERSION="go1.21.1"
GCCGO="gccgo"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD="/Users/username/projects/myproject/go.mod"
GOWORK=""
CGO_CFLAGS="-O2 -g"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-O2 -g"
CGO_FFLAGS="-O2 -g"
CGO_LDFLAGS="-O2 -g"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -arch x86_64 -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/...=/tmp/go-build -gno-record-gcc-switches -fno-common"
Some commonly used environment variables:
GOPATH
: Where Go looks for packagesGOROOT
: The Go installation directoryGOBIN
: Where Go installs binariesGOOS
andGOARCH
: Target operating system and architecture
Cross-Compilation
Go makes it easy to compile for different platforms:
# Build for Windows from a Mac or Linux
GOOS=windows GOARCH=amd64 go build -o myapp.exe main.go
# Build for Linux from any platform
GOOS=linux GOARCH=amd64 go build -o myapp-linux main.go
# Build for macOS
GOOS=darwin GOARCH=amd64 go build -o myapp-mac main.go
Summary
The Go CLI provides a comprehensive set of tools for Go development:
go run
: Compile and run code in one stepgo build
: Compile code into executablesgo install
: Install packages and commandsgo get
: Download and install dependenciesgo mod
: Manage modules and dependenciesgo test
: Test your codego fmt
: Format your codego vet
: Check for common mistakes
These commands form the foundation of the Go development workflow and enable you to efficiently create, test, and deploy Go applications. The simplicity and power of the Go CLI reflect the language's overall design philosophy - straightforward tools that help you get things done effectively.
Additional Resources
Exercises
-
Create a new Go module and write a simple "Hello, World!" program. Use the Go CLI to run and build it.
-
Add a dependency to your project (e.g.,
github.com/gorilla/mux
) usinggo get
. Modify your program to use this dependency. -
Write a function with tests and use
go test
to verify it works correctly. -
Create a Go program that can be cross-compiled for three different platforms.
-
Use
go vet
andgo fmt
to clean up a messy Go file (you can intentionally write some code with formatting issues and unused variables).
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)