Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 01 · 30 minutes

Run and build your first Go program

After this lesson you can
  • Check the Go version and start a module
  • Run a program with `go run` and build it with `go build`
  • Explain why one static binary helps a security team
Lab files of this lesson (3)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

Your team has a Linux server that you may not change. You may not install a language runtime on it, but you may copy one file to it and run it. The lead asks for a small tool that prints the name of the machine and the arguments that you give it, as the first piece of a larger checker. In this lesson you build that tool, copy it as one file, and see that it needs nothing else.

The idea

Go is a compiled language. A tool called the compiler reads your source code and writes a machine-code program. You do not need Go on the machine that runs the program, only on the machine that builds it.

One file that runs without Go
Build machine (has Go)Server (no Go)main.goGo compilerhellohello copyLinux server1234Build machine (has Go)Server (no Go)main.goGo compilerhellohello copyLinux server1234
  1. main.go → Go compiler: go build reads the .go files
  2. Go compiler → hello: your code and the Go runtime in one file
  3. hello → hello copy: you copy that one file
  4. hello copy → Linux server: it runs, with no Go and no library

Three terms matter now:

TermMeaning
ModuleA folder of Go code with a go.mod file. The file holds the module name and the Go version.
PackageA group of .go files in one folder. package main is special: it builds to a program.
BinaryThe finished program file.

A Go binary is usually static: it holds the code it needs, including the Go runtime, and it does not load shared libraries. The Go runtime is helper code that Go adds to every program: it manages memory and runs goroutines (lesson 6). A shared library is code that many programs load from the system when they start. Security teams like this for four reasons. You copy one file and it runs. A tool does not break when the server has other library versions. You can build for another system from your own laptop. And a short list of dependencies is a short list to audit.

Worked example

1. Check your Go version

go is the command of the Go toolchain. Its subcommand version prints the version. The course code needs Go 1.22 or later. If you have no Go yet, do the set-up lesson first.

go version
go version go1.27.3 linux/amd64

Your number may differ. If the command is not found, install Go for your system and open a new terminal.

2. Start a module

mkdir -p makes a directory and the directories above it. cd moves you into a directory. go mod init creates the file go.mod and takes a module name. For a program that you do not publish, any short name is fine.

mkdir -p ~/krlab/go/hello
cd ~/krlab/go/hello
go mod init krlab/hello
go: creating new go.mod: module krlab/hello

cat prints a file.

cat go.mod
module krlab/hello

go 1.27.3

The go line shows the version that you have. The lab zip holds this file with go 1.22, the lowest version that the course needs, so that it builds on every Go from 1.22:

go.mod

module krlab/hello

go 1.22

3. Write the program

Create main.go with the content below. Each word that is new:

  • package main says that this folder builds to a program.
  • import lists the packages that the file uses. A package is code that someone wrote for you to reuse. fmt (format) prints text, and os talks to the operating system.
  • func main() is the function where every program starts.
  • os.Hostname asks the system for its name. os.Args holds the words of the command line. The first word is the program itself, so [1:] skips it.
  • fmt.Println prints its values with spaces between them and a line end.

main.go

package main

import (
	"fmt"
	"os"
)

func main() {
	host, _ := os.Hostname()
	fmt.Println("hello from", host)
	fmt.Println("arguments:", os.Args[1:])
}

The _ throws away the second value that os.Hostname returns, an error. Lesson 3 explains why you should not do this in a real tool.

4. Run it

go run compiles the program into a temporary place and starts it. Everything after . (the current folder) goes to your program.

go run . a b
hello from krbox
arguments: [a b]

5. Build the binary

go build writes the binary into the current folder. The option -o sets its name. ls -l shows the size of the file, and ./hello starts a program in the current folder.

The command that builds the binary
go buildthe Go tool and its subcommand-o hellooption: name the output file hello.build the package in this foldergo buildthe Go tool and its subcommand-o hellooption: name the output file hello.build the package in this folder
go build -o hello .
ls -l hello
./hello x
-rwxrwxr-x 1 you you 2360092 Nov 21 08:34 hello
hello from krbox
arguments: [x]

A program that prints two lines weighs 2.3 MB, because the runtime is inside. Now ask the system what kind of file it is. file tells the type of a file, and ldd lists the shared libraries that a program loads. (ldd does not exist on macOS: use otool -L hello there.)

file hello
ldd hello
hello: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, ...
	not a dynamic executable

statically linked and not a dynamic executable mean that the file needs no other library.

6. Build for another system

Two environment variables choose the target: GOOS is the operating system and GOARCH is the CPU type. This builds a Windows program on Linux, in one second.

A build for another system
GOOS=windowstarget system: WindowsGOARCH=arm64target CPU: ARM, 64 bitgo buildthe same build command-o hello.exe .output file, and the folder to buildGOOS=windowstarget system: WindowsGOARCH=arm64target CPU: ARM, 64 bitgo buildthe same build command-o hello.exe .output file, and the folder to build
GOOS=windows GOARCH=arm64 go build -o hello.exe .
file hello.exe
hello.exe: PE32+ executable for MS Windows 10.00 (console), ARM64, 14 sections

The common pairs are linux/amd64, linux/arm64, darwin/arm64 and windows/amd64. go tool dist list prints all of them.

7. Read a compiler error

Go refuses to build code with an unused import or an unused variable. Change main.go so that it holds this. The sign := declares a variable and gives it a value. Lesson 2 explains it.

package main

import (
	"fmt"
	"os"
)

func main() {
	target := "127.0.0.1"
	fmt.Println("hello, krbox")
}
go run .
# krlab/hello
./main.go:5:2: "os" imported and not used
./main.go:9:2: declared and not used: target

The message gives the file, the line and the column. This strictness feels hard on the first day. It keeps dead code out of your tools.

8. Format the code

Go has one code style, and the tool gofmt (Go format) applies it. In main.go, delete the tab in front of one fmt.Println line and save. Then check.

gofmt -l .
main.go

-l lists the files whose format is not right. gofmt -w main.go fixes the file in place. Most editors run it on save. Run gofmt -l . before you share code: then nobody argues about style.

9. Look things up offline

The toolchain holds the documentation of the standard library, so you need no web page. go doc prints the documentation of a package or a function. With -short, it prints one line for each name.

go doc strings.Cut
go doc -short strings
package strings // import "strings"

func Cut(s, sep string) (before, after string, found bool)
    Cut slices s around the first instance of sep, returning the text before and
    after sep. The found result reports whether sep appears in s. If sep does
    not appear in s, cut returns s, "", false.

func Clone(s string) string
func Compare(a, b string) int
func Contains(s, substr string) bool
...

The list depends on your Go version, so yours may differ. Use go doc whenever a lesson names a function that you want to read about. go help build explains the options of one command in the same way.

Your turn

Build the tool of your lead, with a different job: it must report how many arguments it got. There are no steps here: use what the worked example showed.

In ~/krlab/go/banner:

  1. Start a module named krlab/banner.
  2. Write a program that prints one line: the first argument, then the word of, then the number of arguments. For a b it prints a of 2. (The function len gives the length of a list.)
  3. Run it with go run . red green blue.
  4. Build it with go build -o banner . and run ./banner x y.
  5. Add the line zone := "dmz" as the first line of main, run it, and read the error. Then remove the line.
  6. Break the format of one line, run gofmt -l ., and repair it with gofmt -w main.go.

Answer from your own terminal.

Check yourself

You build `hello` on your laptop and copy it to a server that has no Go. Does it run? What could stop it?

It runs, if the server has the same system and CPU type as the build (here Linux on amd64). It does not need Go or other libraries. A different CPU type, for example arm64, needs a build with GOARCH=arm64.

What is the difference between `go run .` and `go build`?

go run . builds into a temporary place, starts the program and then forgets the file. go build leaves the binary in your folder so that you can keep it, copy it and ship it.

Why does Go reject a program with one unused variable?

The compiler treats an unused variable or import as a likely mistake, for example a check that you wrote and never used. Refusing to build makes you look at it.

Why is the binary of a program that prints two lines 2.3 MB?

It holds the Go runtime (the helper code that manages memory and runs goroutines) and the parts of the standard library that the program uses. This is the price of a file that runs on its own.

Field notes

  • Build releases with go build -trimpath -ldflags="-s -w". -trimpath removes your local folder names from the binary, and -s -w removes symbol and debug data. The file gets smaller (1.5 MB here) and leaks less about your machine. Debugging a stripped binary is harder, so keep an unstripped build for yourself.
  • Static is not guaranteed. Programs that use the net package can link to the C library when cgo is on. CGO_ENABLED=0 go build forces a pure Go build. Check with ldd or file before you ship to a minimal container.
  • A Go binary keeps its module list. go version -m hello prints the Go version and every dependency that went in. This is a cheap way to inventory the tools in your own estate.
  • Strings in a Go binary are plain to read. Do not put secrets in the code: a key in the source is in the binary.
  • GOOS and GOARCH make a cross-build a one-line job. Build and test on every system you ship for, because paths, line endings and permissions differ.