Lesson 01 · 30 minutes
Run and build your first Go program
- 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
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.
- main.go → Go compiler: go build reads the .go files
- Go compiler → hello: your code and the Go runtime in one file
- hello → hello copy: you copy that one file
- hello copy → Linux server: it runs, with no Go and no library
Three terms matter now:
| Term | Meaning |
|---|---|
| Module | A folder of Go code with a go.mod file. The file holds the module name and the Go version. |
| Package | A group of .go files in one folder. package main is special: it builds to a program. |
| Binary | The 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 versiongo version go1.27.3 linux/amd64Your 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/hellogo: creating new go.mod: module krlab/hellocat prints a file.
cat go.modmodule krlab/hello
go 1.27.3The 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.223. Write the program
Create main.go with the content below. Each word that is new:
package mainsays that this folder builds to a program.importlists the packages that the file uses. A package is code that someone wrote for you to reuse.fmt(format) prints text, andostalks to the operating system.func main()is the function where every program starts.os.Hostnameasks the system for its name.os.Argsholds the words of the command line. The first word is the program itself, so[1:]skips it.fmt.Printlnprints 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 bhello 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.
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 hellohello: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, ...
not a dynamic executablestatically 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.
GOOS=windows GOARCH=arm64 go build -o hello.exe .
file hello.exehello.exe: PE32+ executable for MS Windows 10.00 (console), ARM64, 14 sectionsThe 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: targetThe 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 stringspackage 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:
- Start a module named
krlab/banner. - Write a program that prints one line: the first argument, then the word
of, then the number of arguments. Fora bit printsa of 2. (The functionlengives the length of a list.) - Run it with
go run . red green blue. - Build it with
go build -o banner .and run./banner x y. - Add the line
zone := "dmz"as the first line ofmain, run it, and read the error. Then remove the line. - Break the format of one line, run
gofmt -l ., and repair it withgofmt -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".-trimpathremoves your local folder names from the binary, and-s -wremoves 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
netpackage can link to the C library when cgo is on.CGO_ENABLED=0 go buildforces a pure Go build. Check withlddorfilebefore you ship to a minimal container. - A Go binary keeps its module list.
go version -m helloprints 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.
GOOSandGOARCHmake a cross-build a one-line job. Build and test on every system you ship for, because paths, line endings and permissions differ.