Cover of Go: From the First Line to an Online Bookstore

Go: From the First Line to an Online Bookstore

Daulet Baimurzin · English sample edition

The Go gopher was created by Renee French and is used under CC BY 4.0. The cover adapts the character with AI assistance, adding a shopping cart and book.

Start reading · Download the PDF

PREFACE

Why learn to program when AI can write the code?

Ask an AI agent to build a bookstore and it can write the catalog, the cart, and the checkout. Now imagine the first message from a customer. “I bought your book yesterday. Today the price went up, and my order shows the new price. How much did I actually pay?”

You can probably answer half that question already. Yesterday’s purchase should keep yesterday’s price. The other half takes a little detective work. Did the shop save the amount when the customer placed the order? Or does it look up the current price every time someone opens that page? Both versions look fine on the day of the sale. Change the price the next morning and the difference matters to someone.

In this book you will make that sale, change that price, and open the old order yourself. By then you will know where to look. And if an agent writes your next checkout, you will have a test of your own to bring to it.

Your first product is the book you are reading. Your first Go program will print its title in a terminal. By the final chapter, you will be able to sign in as a reader, place an order, confirm a simulated payment, restart the shop, and download the edition you bought. The whole journey takes place on your computer. The payments use a simulator, so you can even arrange for a reply to go missing and see what the shop does next.

Schematic catalog card for the Go book with illustrative formats and price.
Figure 0.1. A schematic catalog card for the Go book; the price is illustrative.

What to do with the keyboard

A boxing coach can show you exactly where to put your feet. Throw a punch yourself and you discover whether you can keep your balance. Programming has a moment like that. You type a few lines, you know what they ought to do, and the screen tells you something else. Now you have a question worth asking.

Try this when you reach the catalog search. Write down two titles in the order you expect to see them. Type the search function yourself, run it, and compare the result with your prediction. Then put a space before the search term. Should that space cost a reader a match? Make your choice, change the program, and write a test that will catch the mistake if it comes back.

Give yourself that first attempt at the keyboard. When you get stuck, show an AI assistant the few lines you wrote, what you expected, and what actually happened. Ask for a hint. Once the program works, close the example and try a variation of your own. You may eventually hand an agent most of the typing. The experience you gain here will help you decide what to ask it to build and how to tell when the work is done.

Three stages, one bookstore

Part I · Junior (chapters 1–14). Start here even if you have never opened a terminal. A title becomes a book, a book joins a catalog, and the catalog becomes a page you can search. An optional workshop lets you turn a long search address into a short link. Stop the server and try that link again. Its disappearance gives you a good reason to turn the page and learn how programs remember.

Part II · Middle (chapters 15–28). Give the shop a database and its readers accounts. Here you will settle the question about yesterday’s price. You will also try opening a purchased book from a second account. It takes two readers to find a mistake that a perfectly happy first customer might never notice.

Part III · Senior (chapters 29–42). Follow the shop through a busy release day. Decide which work can wait, measure a slowdown, and restore a backup. The final check is one a bookseller can appreciate. Open the file that reached the buyer and make sure it really is the edition you meant to sell. The interview questions at the back give you another chance to explain those decisions in your own words.

Working with the examples

The companion archive, Go_English_Code_02-42_working.zip, has a working checkpoint for each chapter from 2 onward. Unpack it and find the chapter folder under examples/. Open a terminal in that folder, next to its go.mod file. Run the checkpoint as supplied, then make a copy for your experiments. Each checkpoint already has its own module.

In chapters 2–9, run the program with go run .. From chapter 10, use go run ./cmd/shop. From chapter 5, run go test ./... to check your changes. A command beginning with go run ./labs/ starts a smaller experiment from the same chapter folder. Chapter 1 walks you through the setup.

For now, pick a book you would like to sell. In chapter 2 you can put its title in your first program. Keep it in mind as you work. There is a particular pleasure in seeing a title you once printed on an empty terminal turn up in a reader’s library.

Part I · Junior · Build the storefront

CHAPTER 1

A Workspace You Can Check

By the end of this chapter, you will have a project folder and a terminal in which the go version command works. You do not need to choose a database or pay for a server yet. First, let us make sure you can save files and run the tools.

A glimpse of the destination

The schematic below previews a possible narrow-screen catalog. We will build the interface gradually; the displayed details are examples.

Schematic mobile catalog with a Go book card and illustrative details.
Figure 1.1. A schematic catalog card for a narrow screen.

A mental picture: your desk

Imagine sitting down to write a letter. There is a folder on your desk, and sheets of paper are inside it. If you leave the letter on a different desk, it will not appear in the folder in front of you. A similar mix-up can happen with a program: you edit one main.go file, while the terminal runs another.

Keep three things in mind: the desk, the folder, and the saved page. The project folder holds the files that belong together. The terminal's current directory determines where a command begins its work. Saving puts the text from your editor into a file that the Go tool can read. An editor can show several projects at once, so seeing the right tab does not prove that the terminal is open in the same folder.

The analogy has a limit: on a computer, a command can be given a full path to a different folder. For now, we will deliberately work from the project folder. Draw a rectangle labeled bookshop, with go.mod inside it. Before running a command, point to the rectangle and say, “I am running the command here.” This small habit can save a long search for the wrong problem.

See the whole process first

In the editor, you write and save main.go; the result is program text on disk. In the terminal, you enter go run .; Go builds and runs the program. Then you read the output and compare it with your prediction. You will create main.go in the next chapter.

A saved file and an open editor tab are not the same thing. If you change text but do not save it, a command may run the previous version. Check for this before rewriting your program.

A terminal is an application that accepts commands. A shell inside the terminal interprets them. On macOS you will commonly encounter zsh; on Linux, bash. On Windows, we will use PowerShell. Where commands differ, the book shows the appropriate alternatives.

Install Go

Open the official installation page: https://go.dev/doc/install. Choose your operating system and processor architecture. Windows uses an MSI installer; macOS uses a PKG installer. On Linux, follow the instructions for the archive matching your architecture. Do not paste commands that remove an older installation unless you understand which directory they will affect.

For this edition, our working target is Go 1.27.3, the latest stable release checked on October 30, 2026. We will run each chapter’s examples on the selected toolchain before that chapter is considered verified. A later patch may be available when you read this; check the official release page and the companion materials. After installing Go, close and reopen your terminal so it receives the updated search settings. To find your installed version, enter the command below without a shell prompt such as $ or >:

go version

For example:

go version go1.27.3 darwin/arm64

The final part depends on your computer: darwin means macOS, and arm64 identifies the processor architecture. Windows and Linux will show different operating-system names. The important point is that Go responds, rather than the shell reporting that the command cannot be found. This is an illustrative output; it does not mean that every example in the book has already been verified with this release.

If Go was already installed, do not remove it at random. Check its version and consult the official upgrade instructions first. Another project on your computer may depend on its own toolchain.

Prepare a folder

Choose a place for learning projects where you have permission to create files. Do not create the new shop inside another project. Open a terminal in your chosen location and run:

mkdir bookshop
cd bookshop

Both commands work in PowerShell and in bash or zsh. The first creates a folder; the second makes it the current directory, so later commands use it as their starting point.

If bookshop already exists, inspect its contents first. For a clean start, choose another name, such as bookshop-study, and use that name in the cd command too.

Check where you are. On macOS or Linux:

pwd
ls

In PowerShell:

Get-Location
Get-ChildItem

The first command shows the path; the second lists the contents. Your path does not have to match a path in this book. What matters is that you can identify your chosen bookshop folder.

Open the folder through your editor's Open Folder menu. Any plain-text editor that saves UTF-8 can work. If you use VS Code, open the entire folder, rather than a file from a neighboring project. Extra extensions are not required for the first chapters.

Give the project a name

In the terminal, while you are inside bookshop, run this command once:

go mod init example.com/bookshop

A go.mod file appears. A Go module is a collection of packages described together by a go.mod file, which records the module path and Go version and can specify dependencies. For now, it is enough to know that this file marks the root of our project. The path example.com/bookshop is an example module name; you do not need to buy the domain or create a website to follow this exercise.

The book's checkpoints are associated with the dake-edu/gopher-shop repository and are located under book/examples/ in the source collection. Their module paths reflect that repository. For a project you create yourself, we use example.com/bookshop to distinguish it from the ready-made examples. The working companion archive contains the English checkpoints under examples/; final distribution will be arranged separately.

The go line in go.mod specifies the module’s minimum required Go version; it is not necessarily the version of the Go toolchain currently running. Use go version to check the toolchain. A newer compatible toolchain may work with a module that declares an older minimum. Do not edit go.mod merely to make its version match a screenshot in another tutorial: the value depends on the tool that created it. Ready-made checkpoints contain their own go.mod files, so do not run go mod init again inside them.

If something goes wrong

• The shell cannot find go: Did installation finish? Did you open a new terminal? Is the Go executable's directory on PATH?

• “go.mod already exists”: A module has already been initialized here; do not initialize it again.

• You cannot create the folder: Choose a directory in your user account where you have write permission.

• Your editor shows different files: Compare the folder open in the editor with the output of pwd or Get-Location.

PATH is a list of directories in which the shell looks for executable programs. Think of it as a list of addresses to check; it does not install a program. Even if an address is correct, the search cannot find an executable that is not there.

A memory aid: a command has parts

In go mod init example.com/bookshop, spaces separate the program name go, the subcommand mod, the action init, and the module name. The slash / is part of the module name; it is not a command that changes directories. In go run ., the final dot is a separate argument meaning the current package.

Do not type shell prompts such as $, >, or sometimes % before a command. The shell displays them. These examples contain no parentheses or braces: they are commands to a tool, not Go source code.

Save main.go, run go run dot from the project folder, then check the program output.
Figure 1.2. Save the file, run the Go command, and check the result.

Recall without looking. Close the example and name the three places: where you edit, what you run, and where you check the result. If you confuse a file path with a module name, check the current directory and open go.mod.

Warm-up

Predict. If you create a file in folder A and run a command from folder B, must the command find that file?

Fill in the blank. Which command changes the current directory to bookshop?

Troubleshoot. Your editor saved a file in bookshop-old, but the terminal is open in bookshop. How can you check the mismatch without reinstalling Go?

Exercises

Required. Create a working folder and a module. Save the output of go version and the path to your folder in environment.txt. In your editor, check that go.mod exists alongside it.

Try your own data. Give the folder a name of your own and check its path again. The folder name and module name do not have to match.

Optional. Find the path to the installed Go command: use command -v go in bash or zsh, or Get-Command go in PowerShell.

Answers and self-check

A command works from its current directory and is not required to search a neighboring folder. Use cd bookshop to change directories. To find the mismatch, compare the terminal's path with the location where your editor saved the file.

You are ready to move on if you can explain where the project is, show its go.mod file, and obtain the Go version. In the next chapter, you will put the first program in that folder.

Part I · Junior · Build the storefront

CHAPTER 2

The Book Appears in the Terminal

You have a working folder and a go.mod file. Now you will write a program that displays the book's title and the three formats planned for its release. The result is small but verifiable: two lines in the right order.

Checkpoint: examples/02-first-program. If you are starting from the prepared checkpoint, open that folder and run its program. If you are typing the project yourself, continue in your own bookshop folder. The English companion archive includes this localized checkpoint under examples/02-first-program.

A mental picture: a note with two instructions

Imagine a note in front of you: “Show the title. Then show the formats.” Read it from top to bottom and the order is clear. Swap the instructions and the formats appear first. We are about to give the program a similarly small sequence of actions.

Our memory aid has three parts: the package, the tool we need, and the instructions. package main associates the file with an executable package; import "fmt" makes the output package available; and main contains two calls to fmt.Println. Picture the braces as a frame around the instructions.

Do not stretch the analogy too far. A computer cannot understand “show it nicely” until we write a specific action. In larger programs, execution can be more complicated than reading from top to bottom. Here we are checking exactly two sequential calls. After running the program, hide the source and reconstruct your note: what belongs to the package, what is imported, and what runs?

The whole program

Create main.go next to go.mod and save the following:

package main

import "fmt"

func main() {
    fmt.Println("Go: From the First Line to an Online Bookstore")
    fmt.Println("Formats: PDF, EPUB, HTML")
}

Before running it, write down the output you expect. Will the quotation marks appear? Will there be a blank line between the title and the formats?

For the first run, use go run .. The word go names the installed tool, run asks it to build and immediately run the program, and the separate dot selects the package in the current directory. For now, the package consists of the Go files alongside one another that begin with package main. Save main.go, then run this command in a terminal open in the same folder:

go run .

Expected output:

Go: From the First Line to an Online Bookstore
Formats: PDF, EPUB, HTML

The program ends after the two print calls, and the terminal prompt reappears. That is expected. go run . does not open the editor or watch for changes: after each saved change, run the command again. We compare this with producing a separate executable below.

Color as a clue

An editor may use syntax highlighting to make parts of the source easier to recognize. For example, it may color package, import, and func as keywords, a quoted string differently from a name, and comments differently from executable code. In this book, the same notation can also be highlighted in an explanatory sentence.

The examples below illustrate categories you will meet later; there is no need to memorize them now:

• package, import, func, var, const, type, if, for, and return are keywords; each has its own meaning.

• priceMinor, fmt, and Println are names; their roles depend on where they appear.

• "Book" is string data inside quotation marks; 42 is a numeric literal.

• // book title starts a comment for the reader of the code.

• { and } mark the boundaries of a block here; later they also appear in composite types and values.

• Parentheses, square brackets, dots, commas, :=, +, and - have meanings determined by their context.

A color used for names does not mean “this must be a variable”: package and function names may have the same color. Predeclared names such as int64, true, and nil are not Go keywords. We will explain them when needed. Highlighting helps you read notation; it does not prove the program correct.

Colors depend on your editor and theme. Go does not prescribe a color for a variable or a string, and a reader or black-and-white screen may change or remove colors altogether. The words, punctuation, captions, and explanations carry the meaning even without color.

Look at the first program. Find import, then find "fmt". Explain what each does without describing its color. The visual cue has done its job if you can recognize the distinction independently of the palette.

Line by line

package main says that the file belongs to the package named main. A program can be built from such a package, but the package declaration alone is not enough: an executable program also needs a main function.

import "fmt" imports a standard-library package for formatting and output. You did not have to download it separately; it comes with Go.

func main() declares a function called main. The parentheses after its name contain its parameters; this function has none. The braces enclose the function body—the statements it executes. We will examine parameters in chapter 5. Go performs program initialization before main, so do not memorize the misleading rule that “main is always the very first line executed.”

In fmt.Println("Book"), the dot selects Println from the fmt package, and the parentheses call it with an argument. The name fmt.Println on its own, without parentheses, does not call the function. Text in double quotes is a string value. The quotes delimit the literal in the source; they do not appear in the output. Println adds a newline after printing.

Within this main function, the calls run in sequence. Swap them and the output lines swap too. Go does not yet know that a book is a product or that the formats represent files. We have passed ordinary text to a printing function.

Formatting without arguments about style

Run:

gofmt -w main.go

gofmt applies standard formatting to Go code; -w writes the result back to the file. It may change indentation. Formatting does not check whether you named the right book and does not replace running the program.

Add extra spaces before one call, save the file, and run gofmt again. Then run the program. Its formatting will change, but the result will stay the same.

Running and building

There are two ways to work with the same source. During learning, use go run . after a change: the tool builds a temporary program and runs it immediately. This works in PowerShell, bash, and zsh. The command does not leave a standalone bookshop executable in the project folder. You do not need to run go build first.

When you want an executable file to keep, use go build. Building does not itself run the program. The -o flag names the output; bookshop is the filename we chose. The last dot again selects the current package.

On macOS or Linux:

go build -o bookshop .
./bookshop

In Windows PowerShell:

go build -o bookshop.exe .
.\bookshop.exe

The first command creates the program; the second runs it. A successful go build normally prints nothing, so use ls or Get-ChildItem to check that the file appeared. The prefixes ./ and .\ tell the shell to run a file from the current directory; .exe is the usual Windows executable extension. These are file paths, not replacements for the dot argument passed to Go.

To check a saved edit, use go run . to build and run immediately. To produce an executable, use go build -o bookshop . (or choose bookshop.exe on Windows). To run an existing executable, use ./bookshop or .\bookshop.exe; that last action does not reread the source.

An executable does not change by itself when you edit main.go. Try this: build the program, change and save the title in the source, and run the existing executable. It shows the old title; a new go run . shows the new one. Build again and compare the outputs.

Do not substitute go run main.go for the book's go run . command. The result may be the same now, but the former selects only the named file. When a second source file appears, its declarations will not be included. go run . selects the package; ordinary runs do not include _test.go files. In chapter 10, the executable package moves to cmd/shop, so the command changes with it.

You do not need Go installed to run this simple compiled example on a compatible system. A macOS binary cannot simply be run as a Windows program: the target operating system and architecture matter. Later we will also account separately for the application's configuration, data, and external services. See the official Go tutorial on compiling and installing an application: https://go.dev/doc/tutorial/compile-install.

Break it safely

Delete the closing quotation mark from the book title. Save the file and run go run .. The build fails. Read the filename and line number; the exact wording can vary between tool versions.

Restore the quotation mark and run the program again. The cause was in the source. Reinstalling Go would not have fixed it.

Reading the notation

package main — this file belongs to the package named main. import "fmt" — import the package identified by the quoted path. func — begin a function declaration. main — the name of the entry function in this program. () after the function name in the declaration — an empty parameter list. { and } — the beginning and end of the function body. fmt.Println — the dot connects the package name to an exported function. ("text") in the call — pass a string argument inside the parentheses. " — the boundary of a string literal; the quotation mark itself is not printed.

The dot in fmt.Println and the dot in go run . have different jobs: the first belongs to Go notation; the second is an argument in a terminal command. Spaces and line breaks can separate parts of the source; spaces inside quotation marks are part of the string.

Go has semicolons, but ordinary Go source usually omits them. Language rules insert them automatically after certain tokens at the end of a line. For now, put a function's opening { on the same line as func main(). Moving it to the next line can change how the source is parsed; gofmt cannot repair every syntax error for you.

The package declaration, fmt import, entry function and Println call form the first Go program.
Figure 2.1. The first program: package, import, entry function, and call.

Recall without looking. Draw three blocks, then write the program again without copying. If you forget a brace, find its matching brace and explain what the pair encloses.

Warm-up

Predict. What changes if you swap the two Println calls?

Fill in the blank. Which package name belongs before the dot in ___.Println("Book")?

Troubleshoot. A message says undefined: Fmt. What differs between the written name and fmt?

Exercises

Required. Add a third line, Status: in preparation. Keep the first two lines unchanged. Save, format, and run the file.

Try your own data. Replace the title with the title of a book you might write. Do not change the format list: the finished project is intended to support PDF, EPUB, and HTML.

Optional. Build the program, then change the title in the source. Compare the existing executable with go run . and explain the difference before building again.

Explain in your own words

Why does saving the file matter before a run? What does import do? Why does go build not display the title in the terminal?

Answers

The order of the calls determines the order of the lines. The package name is lowercase fmt: capitalization matters. The additional line is another call, fmt.Println("Status: in preparation"), inside main after the first two calls.

A build reads saved files. import makes the named package available. go build creates an executable; it does not run that executable itself.

The shop now has its first public information: a title and formats. For the moment, both are written directly in print calls. In the next chapter we will separate data from the actions performed on it.

Part I · Junior · Build the storefront

CHAPTER 3

A Title, a Price, and a Publication State

We can already print two lines. But a price will participate in calculations, and a publication state will determine whether a product is available. Our data therefore needs suitable types.

Checkpoint: examples/03-values. If you are typing the project yourself, save your chapter 2 folder first and work in a separate copy for this chapter. Keep its go.mod, and replace main.go with the complete shop example shown below. The price is illustrative; it is not the announced price of a future book. The working companion archive contains the examples for chapters 2–42.

Two paths through this chapter

If you have the prepared chapter 3 checkpoint, open its directory. Its go.mod identifies the module, main.go contains the shop example, and labs/01-values/main.go contains a separate experiment. Open a terminal in the checkpoint's root—the directory containing go.mod.

If you are typing the files yourself, create a fresh chapter 3 folder containing your go.mod. For the experiment, create the directories labs and labs/01-values inside it, then save the complete lab listing below as labs/01-values/main.go. Your terminal stays in the chapter 3 root. Create or replace main.go with the shop listing only when you reach “The complete shop example.” Do not run go mod init inside the lab directory: it belongs to the chapter's module.

A mental picture: a labeled price tag

Imagine a price tag with a place for the title at the top, a price underneath, and a mark at the side saying whether to show the book to customers. To change the amount, you do not need to rewrite the entire tag. You find the right place by its label.

A variable's name helps you find a value in a program. Its type determines which values and operations are allowed. A title string and an integer price do different jobs: adding a title to a discount percentage does not make sense. A variable's current value can change; const declares a constant to which you cannot assign a new value.

On paper, you can cross out anything. Go is stricter: the compiler checks whether operations are allowed. The price-tag image helps connect a name with its purpose, but the language supplies the precise rules. Draw three labeled places and fill each with an example value. Where would false make sense? Where would it violate your intention?

Before the price: values, variables, and types

A value is a particular piece of data: the number 150, the string "Go", or the Boolean value false. A variable is a named place holding a value of a particular type. A type determines the allowed values and operations. These are three different ideas: priceMinor is a name, int64 is a type, and 150 can be its current value. Changing the value does not change the variable's type.

A literal writes a value directly in the source. The literals 150 and "150" differ: one is a number, the other a string containing three digit characters. The compiler does not guess whether you intend to calculate an amount or print an identifier. We will handle conversion of user-entered text to a number, including possible errors, when we study forms. For now, we work with numeric values.

Three ways to declare a variable

Inside main, these are alternatives—not three declarations to paste one after another into the same block:

var quantity int       // an int with its zero value, 0
var quantity int = 2   // an int with an explicit initial value
quantity := 2          // a new variable; this literal gives it type int

In a short declaration, := is one operator. To change a variable already declared, write quantity = 3. Writing quantity := 3 again in the same block, with no new name on the left, produces an error such as “no new variables on left side of :=”.

A block is a group of statements inside { and }. For now, the variables declared in main are accessible from their declarations to the end of that block. They cannot be used before their declarations. Chapter 4 introduces nested blocks, and chapter 5 introduces separate functions with their own parameters.

Types we need first

bool holds true or false, useful for whether a book is published. string holds a sequence of bytes, used for titles and currency codes. Chapter 6 examines text in detail. int is a signed integer, 32 or 64 bits depending on the platform. We use it for quantities and indexes. int64 is a signed 64-bit integer. We use it for amounts in the smallest unit of our model currency. float64 is a floating-point number, generally approximate. It is useful for measurements, but not for prices in our model.

Go also has int8, int16, int32; unsigned uint8, uint16, uint32, uint64 and uint; and float32. Size limits the range: int8 allows −128 through 127, while uint8 allows 0 through 255. An unsigned type does not protect arithmetic from overflow. byte and rune are aliases for uint8 and int32; chapter 6 explains their roles in text. uintptr and complex numbers are outside these exercises and are not prerequisites for the next chapter.

The literal 2 in quantity := 2 produces an int; 2.5 produces a float64, "Go" a string, and true a bool. In fmt.Printf, %T prints a value's type and %t prints a bool. These are formatting verbs in a string, not declarations of types.

Zero values and copying

A declaration without a value does not leave random garbage. Go supplies the type's zero value: 0 for an integer, "" for a string, and false for a bool. A value allowed by the language can still be invalid for the application: a title rule must reject an empty title separately if that is the intended behavior.

If you write otherTitle := title, the second variable receives the current string value. It does not become another name that automatically follows later changes to title. If title is assigned another string, otherTitle retains the earlier one. This is a statement about assigning string values; it is not a promise that all future composite data is independent. Shared slice storage appears in chapter 7.

Different numeric types do not combine automatically

A quantity of type int and a priceMinor of type int64 have different types. Between numbers, * means multiplication. To multiply these two values, write int64(quantity) * priceMinor. Although it resembles a function call, int64(quantity) is a conversion. For our quantity of 2, the converted value is still 2; the original quantity variable remains an int.

A conversion is not universal validation. Converting a large integer to a narrower integer type can lose information. This notation does not parse a string of digits either. Do not insert conversions at random merely to silence the compiler: first determine the units and allowed range.

const percent = 10 declares an untyped numeric constant. It can be assigned to an int64 if the value is representable by that type. By contrast, const percent int64 = 10 gives the constant a type immediately. Unlike a variable, a constant does not receive a new value. A constant 300 cannot be assigned to uint8: the compiler detects that it is out of range before the program runs.

A small experiment before the price tag

Save this complete listing as labs/01-values/main.go. In a prepared checkpoint it is already there. Create the nested folders if you are working from your own chapter folder. Keep the terminal at the root containing go.mod; do not modify the shop's main.go for this experiment.

package main

import "fmt"

func main() {
    var title string
    var priceMinor int64
    var published bool
    fmt.Printf("title=[%s], price=%d, published=%t\n", title, priceMinor, published)
    title = "Go"
    otherTitle := title
    title = "Go shop"
    fmt.Println(title)
    fmt.Println(otherTitle)
    quantity := 2
    priceMinor = 150
    total := int64(quantity) * priceMinor
    fmt.Printf("%T %T %d\n", quantity, priceMinor, total)
    const percent = 10
    var discount int64 = percent
    fmt.Println(discount)
}

Before running it, write down both title values after each assignment. Then, from the chapter root, run:

go run ./labs/01-values

The path after run selects the lab package; it does not change your terminal's current directory. In contrast, go run . selects the main package in the chapter root.

Expected output:

title=[], price=0, published=false
Go shop
Go
int int64 300
10

The brackets on the first line are printed characters surrounding an empty string. The remaining lines show the two different strings, two numeric types, the total 300, and a constant assigned to a variable of a suitable type.

Change and explain. Replace the quantity 2 with 3: the total becomes 450, but the type names do not change. In a copy of the lab, remove int64(...) around quantity: the compiler should reject the multiplication because the operands have different types. Restore it. Then try assigning the string "150" to priceMinor and explain why this is another type mismatch.

Check before the shop. Without looking at the listing, declare a zero-valued bool, assign true to it, and print it. Then declare two independent variables with the same initial string value and change only one. If you cannot explain the result, revisit declarations and copying before continuing.

The complete shop example

Save this as main.go in the chapter root, next to go.mod. The example deliberately retains KZT, the Kazakhstani tenge, from the original project. For this exercise the amount is stored in hundredths of one tenge; the price and currency are examples, not a recommendation for a real payment system.

package main

import "fmt"

func main() {
    const currency = "KZT"
    const minorPerUnit = 100
    var priceMinor int64 = 249900
    title := "Go: From the First Line to an Online Bookstore"
    published := false

    fmt.Println(title)
    fmt.Printf("Price: %d.%02d %s\n", priceMinor/minorPerUnit, priceMinor%minorPerUnit, currency)
    fmt.Println("Published:", published)
    published = true
    fmt.Println("Published:", published)
}

Predict the final two lines, then save the file and run go run . from the chapter root. Expected output:

Go: From the First Line to an Online Bookstore
Price: 2499.00 KZT
Published: false
Published: true

The same variable appears in output twice. We changed its value between the calls, so the results differ.

A value and its name

title := "..." creates a variable and gives it a string value. Go infers its type from the right-hand side. Short declarations with := are used inside functions.

published := false creates a bool variable. A bool has two values, true and false, making it suitable for a question with two answers: is this book published?

published = true changes the value of an existing variable. It uses =, not :=. Assigning another value to the existing name does not require a new declaration.

var priceMinor int64 = 249900 is a more explicit form: we chose int64, a signed integer type with a fixed width. The width of int, often used for counters and indexes, depends on the architecture. For amounts in this model we will use a fixed-width integer type.

Without an initial value, Go supplies a zero value: 0 for an integer, an empty string for string, and false for bool. This is a language rule, not a business decision. Do not assume a zero price is allowed until the shop defines its policy on free books.

A constant does not change

const currency = "KZT" declares a constant. The program cannot assign a different value to it at runtime. This example uses one currency, so its currency code stays fixed.

That does not mean every shop must use only one currency. In a multi-currency shop, currency would be part of the data, and conversion and rounding rules would need separate definitions.

minorPerUnit is the number of minor units in one major unit in our educational KZT representation: 100. The name explains the number's role. An unnamed 100 might instead mean a percentage, a length limit, or a number of items.

Why the price is an integer

We store 2499.00 KZT as 249900 minor units. Integer arithmetic gives us an explicit unit of account and forces us to decide what to do when a calculation produces a fraction of a minor unit.

float64 is useful for approximate calculations, measurements, and many scientific tasks. However, many decimal fractions cannot be represented exactly in binary floating point. For money rules, we want a reproducible unit, not an approximation that merely looks correct when printed.

Integers have limits too. Using int64 does not itself prevent multiplication overflow. In chapter 5 we will constrain the input price before calculation and test the boundaries. Later we will bring amount and currency together in a model so their units cannot be confused.

Where the decimal point and zeros come from

Integer division priceMinor / minorPerUnit gives the whole-unit part. The % operator gives the remainder. For 249900, those are 2499 and 0.

fmt.Printf prints according to a format string. In our format:

%d    an integer in decimal notation
%02d  an integer at least two characters wide, padded with a leading zero
%s    a string
\n    a newline

The remainder 0 therefore appears as 00; a remainder of 5 would appear as 05. Unlike Println, Printf does not append a newline automatically: our format string includes it.

This display rule assumes a nonnegative price. It is not a complete formatter for negative amounts or all currencies. Those rules need separate treatment when required.

Reading the new notation

:=              declare a variable and give it an initial value
=               assign a new value to an existing variable
const           declare a constant
var             declare a variable
int64, string, bool   names of types
249900          an integer literal without quotation marks
false, true     Boolean values without quotation marks
,               separates arguments in this Printf call
/ and %         integer division and remainder, between numbers
%d              a formatting verb inside the Printf format string

Read a visible symbol in context. Outside a string, % performs a Go arithmetic operation; inside the format string, %02d is interpreted by Printf. The backslash in \n begins an escape sequence for a newline; it does not produce two visible characters.

Three boxes identify title as string, priceMinor as int64 in minor units, and published as bool.
Figure 3.1. Book data types — title, price in minor units, and publication state.

Check your understanding. Identify the assignment that changes stored data, then identify the place that only determines how output looks. If you think % has the same role in both places, reread the price explanation.

Warm-up

Predict. What price is displayed when priceMinor is 105?

Fill in the blank. To change a published book back to a draft, write published ___ false.

Troubleshoot. Someone wrote priceMinor = "249900". Why is that not the same value as the number 249900?

Exercises

Required. Set the price to 350050. The program should print Price: 3500.50 KZT. The second publication-state line must still read Published: true.

Try your own data. Choose a positive price whose final two digits are 05. Predict the output before running the program.

Optional. Try to assign a different value to the constant currency. Read the error, then undo the change.

Explain in your own words

How does a declaration differ from an assignment? Why is an amount without a currency incomplete? Why does using an integer type not eliminate the need to check the range?

Answers

105 minor units produce 1.05 KZT. Assignment uses =. A quoted value has string type, while priceMinor was declared as an integer; the two types are not directly assignable.

For the required exercise, change only the initial price. Do not change the output format just to fit one answer: it must also work with the earlier price.

Our book now has three kinds of data. Next we will make decisions based on those data instead of always printing the same thing.

Part I · Junior · Build the storefront

CHAPTER 4 — Which Editions Can We Show?

A book may still be a draft, and an older edition may have been withdrawn from sale. We will check three edition numbers and report which ones are available. This catalog exercise does not remove previously purchased books from a customer's library; access to purchased editions is a separate rule.

Checkpoint: examples/04-conditions. If you are typing the examples yourself, create a separate chapter folder, copy your go.mod into it, and create main.go from the complete listing below. Keep the previous chapter's folder: replacing a file in this exercise does not erase the history of your work. For the two labs, create labs/01-choices and labs/02-loops under the chapter root, saving each complete listing as main.go in its own folder. Run all commands from the root containing go.mod.

A door and three cards

Imagine three edition cards on a table. A door before the display says “Show only published books.” First check whether the door is open. Then take one card at a time. The second edition is withdrawn, so put it aside and take the next card.

In the program, if chooses an action and for repeats steps. continue ends work on the current card and moves to the next loop iteration; break ends the loop altogether. After the second card, will you reach for the third, or put away the entire stack? Draw the three cards, cross out the second, and keep the third. Which operation gives that result?

The door is a picture of a choice, not an object in the program. The condition itself must produce a Boolean value.

Choosing without repetition

A condition answers a question; branching chooses which block to execute. In chapter 3 we changed values in sequence. Now the program can skip statements. An if condition must have type bool: the number 1 or a nonempty string does not itself stand for true.

if runs a block for a true condition; else runs its alternative. An else if chain asks another question only when the previous answer was false. The first matching branch executes; later branches in the chain do not. Use separate if statements when actions should be independent.

The comparisons ==, !=, <, <=, >, and >= produce bool values. A single = assigns, so quantity = 0 is not the question “is quantity zero?” The ! operator negates a Boolean.

A B A && B A || B false false false false false true false true true false false true true true true true

The && operator does not evaluate its right side if its left side is false. The || operator does not evaluate its right side if its left side is true. This is short-circuit evaluation. For example, check that a divisor is nonzero before evaluating division on the right of &&. Parentheses clarify grouping; do not reorder checks when the right side depends on the left side's guarantee.

Choosing one case with switch

switch status compares status with the values after case. A matching case runs its block; default handles no match. Go exits an ordinary switch case automatically, so you need not write break after every case. This differs from breaking out of a loop. A type switch is another construct and will appear only after interfaces; fallthrough is not needed here.

Save this separate lab as labs/01-choices/main.go:

package main
import "fmt"
func main() {
    published := true
    quantity := 0
    if !published {
        fmt.Println("Draft")
    } else if quantity == 0 {
        fmt.Println("No copies available")
    } else {
        fmt.Println("Available to choose")
    }
    fmt.Println(published && quantity > 0)
    fmt.Println(published || quantity > 0)
    status := "draft"
    switch status {
    case "draft":
        fmt.Println("In preparation")
    case "published":
        fmt.Println("On display")
    default:
        fmt.Println("Unknown status")
    }
}

From the chapter root run go run ./labs/01-choices. Expected output:

No copies available
false
true
In preparation

published is true but quantity is zero: the second branch runs, AND is false, and OR is true. The switch uses the separate status string, not the earlier condition's result. Set quantity to 2 and predict the first three lines. Then set published to false. Finally use an unknown status to see the default branch. These changes test different decisions.

Where a variable is visible

A variable declared inside a branch's braces is not visible after that branch. If you need the result after the if, declare it before the branch and assign with = inside it. A new := in an inner block can declare a different variable that shadows the outer one; the outer value then remains unchanged. Scope describes where a name can be used in source code, not the lifetime of its data. We will discuss pointers and closures later.

Repetition without nested decisions

Go uses for for several loop forms:

for i := 1; i <= 3; i++ { ... }  // counter, boundary, regular step
for remaining > 0 { ... }        // repeat while a condition is true
for { ... }                      // stop from inside the body

The ellipses stand for a body; do not copy them as code. A condition is checked before the body, so the body may execute zero times. The body must make progress toward stopping. In remaining = remaining - 1, the subtraction is assigned back to the same variable. A condition-only loop has no separate automatic step.

Save as labs/02-loops/main.go:

package main
import "fmt"
func main() {
    for edition := 1; edition <= 3; edition++ {
        fmt.Println("Edition", edition)
    }
    remaining := 2
    for remaining > 0 {
        fmt.Println("Remaining", remaining)
        remaining = remaining - 1
    }
    number := 0
    for {
        number++
        if number == 2 { continue }
        if number == 4 { break }
        fmt.Println("Selected", number)
    }
}

Run go run ./labs/02-loops. Expected output:

Edition 1
Edition 2
Edition 3
Remaining 2
Remaining 1
Selected 1
Selected 3

The first loop executes three times. In the second, remaining becomes zero after printing 1, so the next condition is false. In the third, incrementing happens before the checks: continue skips 2 and break stops at 4. No infinite loop is intended.

Trace the second loop on paper: 2 > 0, 1 > 0, then 0 > 0. The last check does not enter the body. Try starting at zero; predict which two lines disappear, then restore 2.

Before combining ideas, write one choice for “draft / published” and a separate loop printing 1, 2, 3. Explain why continue still permits a next iteration and break does not.

The complete shop example

Save this as main.go in the chapter root:

package main
import "fmt"
func main() {
    published := true
    for edition := 1; edition <= 3; edition++ {
        if !published {
            fmt.Println("Book in preparation")
            break
        }
        if edition == 2 {
            fmt.Println("Edition", edition, "withdrawn from sale")
            continue
        }
        fmt.Println("Available edition", edition)
    }
}

Mark which statements run for edition 2. Then run go run .:

Available edition 1
Edition 2 withdrawn from sale
Available edition 3

Edition 2 is not lost: it receives an explicit, different result.

Reading the condition and loop

if edition == 2 asks whether the edition equals two. = assigns; == compares. !published means “not published.” Comparisons also include <, <=, >, >=, and !=; their applicability depends on operand types. Here we use integers and a bool.

In for edition := 1; edition <= 3; edition++, the first part creates the counter before the loop, the second is checked before each body, and the third runs after each iteration. The values are 1, 2, 3; at 4 the condition is false. edition is declared in the loop header and cannot be used after the loop. edition++ is an increment statement, not an expression to put inside a print call.

continue ends the current iteration. In this form of for, the increment then runs, followed by the condition check. break exits the entire loop. Set published to false: the program prints “Book in preparation” once and stops iterating. The loop determines the boundary of these operations.

Check boundaries: replace <= 3 with < 3 and edition 3 disappears. Restore <= and start at 4; the body executes zero times. Restore the original, then remove edition++ while retaining both semicolons. With published true the program repeats indefinitely; stop it with Ctrl+C and restore the step. Do not leave it running.

Notation: for begins a loop; semicolons separate initialization, condition, and post statement; <= means less than or equal; ++ increments; if runs a block when true; ! negates; == compares; break exits; continue ends the current iteration. Nested closing braces occur in reverse order: inner if, outer for, then main. Go does not require parentheses around an if condition.

Initialize edition to 1; check whether edition is at most 3; execute the body and increment. Return to the check; false ends the loop.
Figure 4.1. The for loop — initialization, condition, body, and step.

Trace editions 1, 2, and 3 before running: which conditions hold and where does each iteration end?

Warm-up

Predict: how many lines appear when published is false? Fill in: which includes the upper boundary, < or <=? Troubleshoot: if continue is removed, why does a withdrawn edition also print as available?

Exercises

Required: iterate from 1 through 4, withdrawing edition 3. Predict and verify:

Available edition 1
Available edition 2
Edition 3 withdrawn from sale
Available edition 4

Try your own data: choose a different withdrawn number and predict all lines. Optional: withdraw two editions using separate conditions, then combine the check with || and compare readability.

Answers

A draft produces one line. <= includes the upper boundary. Without continue, execution proceeds after the withdrawal message and prints the ordinary line in the same iteration. For the required exercise, change the upper bound to 4 and the withdrawal check to edition == 3; retain the starting value 1.

We can now repeat actions and choose them based on data. Next we will move a discount rule into a function and preserve its expected behavior with tests.

Part I · Junior · Build the storefront

CHAPTER 5 — A Pricing Rule and the First Test

Chapter 3 only displayed the price. Now we will add a discount. We want to write the calculation once and call it from different places, rather than copy its arithmetic throughout the shop.

Checkpoint: examples/05-functions. You need conditions, integer division, and variables; structs and collections are not yet prerequisites. If typing the project yourself, prepare a separate folder containing your go.mod, the main.go listing below, and the main_test.go from the first-test section. In the prepared checkpoint main_test.go already exists: add new tests there without duplicating function names. For the lab, create labs/01-functions/main.go and run its command from the chapter root.

A calculation card

Imagine a cashier's card with two blanks: price and discount. Below are calculation steps, followed by space for the result. The same card can be used for different books.

Our function has two input parameters. A call supplies arguments: a particular price and percentage. The function returns a new price and a flag indicating whether the inputs are valid. A percentage above 100 must not produce an arbitrary number presented as success.

The memory aid is: two inputs, validation, two outputs. This describes our function, not every function in Go. Functions can have different numbers of parameters and results, and some modify external state. Starting with a self-contained rule makes checking easier. Before reading the code, trace a price of 100 with a 10 percent discount: what belongs in each output?

What happens in a call

A named function declares a section of a program with specified parameters and results. Anonymous functions also exist; chapter 9 introduces them. A declaration describes what happens; a call starts those actions. Placing a declaration above main does not make its body execute before main: an ordinary function waits to be called.

Consider two simpler forms:

func announce(title string)                 // one parameter, no result
func total(priceMinor int64, quantity int64) int64 // two parameters, one result

Complete bodies follow. The type after the parameter list describes the result. A call to announce returns no number that can be assigned. Printing a value and returning it are different actions.

Parameters and arguments

priceMinor and quantity in the total declaration are parameters. In total(150, quantity), 150 and the caller's quantity value are arguments. Order matters: the first argument supplies the first parameter. Parameters are already declared; do not redeclare them inside the function with :=.

Argument values are copied. Assigning a new number to a parameter does not change the caller's variable. Identical spellings of quantity in two functions do not connect those variables.

return expression ends the current call and gives its value to the caller, which continues after the call. Statements after an executed return in that function do not run. A function with no results can use a bare return; main also has no result. Every normally completing path of a function that declares results must provide them.

A complete lab: printing, returning, and copying a parameter

Save this as labs/01-functions/main.go:

package main
import "fmt"
func announce(title string) { fmt.Println("Book:", title) }
func total(priceMinor int64, quantity int64) int64 { return priceMinor * quantity }
func changeQuantity(quantity int64) {
    quantity = 10
    fmt.Println("Inside:", quantity)
}
func main() {
    announce("Go")
    var quantity int64 = 2
    amount := total(150, quantity)
    fmt.Println("Total:", amount)
    changeQuantity(quantity)
    fmt.Println("Outside:", quantity)
}

From the module root, run go run ./labs/01-functions:

Book: Go
Total: 300
Inside: 10
Outside: 2

Trace the call: main passes 150 and 2; the parameters receive those values; return gives 300 to the caller; amount receives it; Println displays it. total itself prints nothing. changeQuantity changes its own parameter, so the caller still prints 2. A pointer later can give access to the original value; Go still passes argument values by value.

Pass quantity 3 to total and predict 450. Restore the source, then replace fmt.Println("Total:", amount) with fmt.Println("Total:", total(150, quantity)) and remove the now-unused amount := ... declaration: the call calculates again. Go rejects an unused local variable, so leaving that declaration in place would prevent the program from compiling. Merely mentioning a function name without () does not call it.

On your own, write double(value int64) int64 that returns twice its input without printing. Call it with 7 and print the result from main: 14. If the function prints 14 but you cannot assign its result, you have confused printing with returning.

From one result to two

A valid discount can produce zero, and invalid arguments must also be reported. One number cannot distinguish those cases. Our function returns a number and a Boolean success flag. (int64, bool) specifies their order; return 0, false returns two values in that order.

In price, ok := priceAfterDiscount(...), the right side is evaluated and then the results are assigned. ok is a conventional name, not a keyword. An intentionally unused result can be assigned to _, the blank identifier, whose value cannot later be retrieved. Do not discard the success flag merely to make a price calculation shorter.

Recursion, variadic parameters, and functions returning functions are not needed in this experiment. They are language features, but require their own preparation.

Agree on the result first

The educational rule accepts a price in minor currency units and an integer discount percentage. Valid prices are 0 through 100000000, and valid percentages 0 through 100, inclusive. The price bound is chosen for this exercise and safe calculation, not as a universal commercial limit.

Calculate the discount first and discard any fractional minor unit in the discount. Ten percent of 105 is 10.5; the discount becomes 10, so the customer pays 95. This is a particular rounding rule favoring the seller. Another shop may choose a different rule, but must state and test it.

On invalid arguments the function reports failure. Its numeric result must not be used as a price in that case.

The complete program

Save as main.go in the chapter root:

package main
import "fmt"

// priceAfterDiscount accepts a price in minor currency units.
// Price must be 0 through 100000000; percent must be 0 through 100.
// A fractional minor unit in the discount is discarded in the seller's favor.
func priceAfterDiscount(priceMinor int64, percent int64) (int64, bool) {
    if priceMinor < 0 || priceMinor > 100000000 {
        return 0, false
    }
    if percent < 0 || percent > 100 {
        return 0, false
    }
    discountMinor := priceMinor * percent / 100
    return priceMinor - discountMinor, true
}

func main() {
    priceMinor, ok := priceAfterDiscount(249900, 10)
    if !ok {
        fmt.Println("Invalid price or discount")
        return
    }
    fmt.Println("Amount due:", priceMinor, "minor units of KZT")
}

Run go run .:

Amount due: 224910 minor units of KZT

Two outputs distinguish a free book from an error: a valid zero price produces (0, true), while invalid input produces (0, false). The function returns its result rather than printing, so a terminal program, an HTTP handler, or a test can use the same rule without capturing screen output. Check ok before using the price. Later, when different reasons for failure matter, we can return an error value instead.

The parameter priceMinor and the variable of the same spelling in main are different variables in different scopes. An integer argument is copied; this function does not modify the caller's variable.

Why validate before multiplying?

The || operator means “or.” A price is invalid if below zero or above the upper bound; the percentage is checked separately. The largest allowed product is 100000000 × 100 = 10000000000, which fits in int64. A larger arbitrary price is rejected before multiplication. Checking after arithmetic could be too late: once overflow has changed a result, a later comparison cannot restore its original meaning.

A check that stays with the code

Create main_test.go next to main.go. Before reading it: Go's test runner creates a testing.T reporting object and gives the test access to it through t *testing.T. The star here denotes a pointer, not multiplication; t.Fatalf calls a method associated with that object. You do not create the object yourself or change the test signature. Chapter 8 introduces pointers and methods in detail.

package main
import "testing"
func TestPriceAfterDiscount(t *testing.T) {
    got, ok := priceAfterDiscount(249900, 10)
    if !ok || got != 224910 {
        t.Fatalf("got (%d, %t), want (224910, true)", got, ok)
    }
}

Run from the folder containing go.mod:

go test ./...

Go builds and runs checks in _test.go files. The argument ./... selects packages in this module's current directory and subdirectories: ./ is a relative path, and ... is a Go tool pattern. Type all three dots; they are not omitted text. A successful package reports ok. FAIL means a failed test or build: read the preceding message. [no test files] means no tests were found, not that an exercise passed. go run . executes main but does not run TestPriceAfterDiscount; both commands have different purposes.

The time or a (cached) marker may differ. To force a fresh run, use go test -count=1 ./....

TestPriceAfterDiscount starts with Test. got names the observed value. The condition checks both the value and success flag. t.Fatalf marks the test failed, prints a formatted message, and stops that test. t.Fatal also stops a test but receives values rather than a format string. In Fatalf, %d formats an integer and %t a bool. Showing observed and expected values makes failures easier to investigate.

Make sure the test can fail

Temporarily replace priceMinor - discountMinor with priceMinor + discountMinor. This plausible sign mistake increases the price. Run the test and find the mismatch. Restore the minus sign and run it again. A passing test is useful alongside an understanding of the error it can detect.

Do not compute an expected result with the same formula under test: the same mistake could occur in both halves and make the comparison pass.

Boundaries matter more than one successful value

Price Discount Result Success 249900 0 249900 true 249900 100 0 true 105 10 95 true 0 10 0 true -1 10 do not use false 100 101 do not use false

The full checkpoint also tests a negative discount, the maximum price, and one above that limit. Tests do not prove correctness for every conceivable program; they preserve important examples of our rule.

Reading the notation

// starts a comment through the end of a line. (priceMinor int64, percent int64) declares two parameters; (int64, bool) declares two ordered results. return ends a call. || means logical OR. In the arithmetic, * and - mean multiplication and subtraction. != means not equal. _ deliberately discards a result. In t *testing.T the star denotes a pointer, while t.Fatalf is a method call.

Read if !ok || got != 224910 as “there was no success OR the number differed.” The right side of || is evaluated only if the left is false. Multiplication and division take precedence over subtraction; operators of the same precedence group left to right. Parentheses can change grouping. %t displays a bool and \n in a string represents a newline. Comments describe a contract; the compiler does not prove code meets it, so we write checks.

Validate the input price and percentage. If valid, calculate the integer discount and return the price and success flag; invalid input stops the calculation.
Figure 5.1. Validate inputs, calculate the discount, and return the result.

Explain the two meanings of * in this chapter and show where invalid input stops the calculation before multiplication.

Warm-up

Predict: what does priceAfterDiscount(105, 100) return? Fill in: may you treat price as valid before checking ok? Troubleshoot: why does a test that checks only for a zero result fail to distinguish a free book from an error?

Exercises

Required: write TestSmallDiscount for price 105 and percentage 1; expect 104 and true. Calculate the result on paper first, then run the test. Do not change the function to fit an incorrect expectation.

Try your own data: choose a price and percentage producing a fractional discount and explain the result under our rounding rule. Optional: in a separate copy, round the discount upward to a whole minor unit. State new expectations for 105 and 10% before changing the function and tests; preserve the original checkpoint.

Answers

A 100% discount on a valid price gives (0, true). Check ok before using the number as a price. A free-book test must check both the zero and success flag. For the required exercise, integer arithmetic gives 105 * 1 / 100 = 1, so the price is 104. Follow the first test's shape, changing arguments, expectation, and test name.

The project now has an independent rule and an automated check. Next we examine a book title and why its byte length differs from the number of visible letters.

Part I · Junior · Build the storefront

CHAPTER 6 — How Many Letters Are in a Book Title?

A book title should work with text in different languages. Measuring it with the wrong unit can reject a short title, and cutting its bytes can make the result unreadable. We will measure a string and define a title rule: check its encoding, trim whitespace at the edges, and limit its length.

Checkpoint: examples/06-strings. If typing the project yourself, prepare a separate chapter folder with go.mod and the main.go and title.go below. Obtain title_test.go from the companion checkpoint; keep the discount tests in your chapter 5 folder. The working companion archive for chapters 2–42 contains that test file. Chapter 8 will bring title and price together.

A mosaic and its pieces

Look at ӘGo. You see three characters. Imagine constructing each from little pieces and measuring the box by its pieces, not its characters. In UTF-8, G and o each need one byte; Ә needs two. Thus len("ӘGo") is 4: len counts string bytes. A range loop decodes Unicode code points, called runes in Go. There are three, starting at byte offsets 0, 2, and 3. Draw four squares and connect the first two: the next character begins at offset 2.

The mosaic is only a memory aid. A rune does not always correspond to one character perceived by a person: a letter and a combining mark can be multiple code points. Ask what you need to count—bytes, code points, or user-perceived characters.

Strings and runes

This chapter uses variables, function calls, and loops from chapters 3–5. Separate three questions: what is stored, how is it written in source, and what does a person see?

"ӘGo" is a string literal in double quotes. A string holds a sequence of bytes. 'Ә' is a rune literal in single quotes: one Unicode code point. In var letter rune = 'Ә', rune is an alias for int32. It is a number associated with a Unicode code point, not a one-character string.

Ә is U+04D8, decimal 1240. UTF-8 encodes it with two bytes; byte values are not the code-point number. %c displays a character from a rune value, and %d displays its number. A byte contains eight bits and holds 0 through 255; byte is an alias for uint8. text[0] is the byte at index zero, possibly only part of a UTF-8 character.

Quotes and escapes

In an interpreted string literal, "Go\nshop" contains a newline; \t is a tab, \" a double quote, and \\ a backslash. In a raw string literal between backticks, a backslash does not itself start an escape. Quotes delimit literals and are not part of their values. %q shows an escaped, quoted representation, so visible backslashes in its output are not necessarily individual characters in the original value.

Walking text: an index is not a letter number

In for offset, value := range text, each iteration gives the starting byte offset and a rune. The types are int and rune. In valid UTF-8, moving to the next rune may skip more than one byte. Use _ when the offset is not needed.

Save this lab as labs/01-text/main.go under the chapter root:

package main
import (
    "fmt"
    "unicode/utf8"
)
func main() {
    text := "ӘGo"
    var letter rune = 'Ә'
    fmt.Println(len(text), utf8.RuneCountInString(text))
    fmt.Printf("%T %c %d\n", letter, letter, letter)
    fmt.Printf("First byte: %d\n", text[0])
    for offset, value := range text {
        fmt.Printf("%d %c\n", offset, value)
    }
    fmt.Printf("%q\n", "Go\nshop")
    fmt.Printf("%q\n", `Go\nshop`)
    old := text
    text = "Go" + " shop"
    fmt.Println(old, text)
}

Run go run ./labs/01-text:

4 3
int32 Ә 1240
First byte: 211
0 Ә
2 G
3 o
"Go\nshop"
"Go\\nshop"
ӘGo Go shop

Four bytes and three runes answer different questions. Code point 1240 is not the first byte 211. The offsets are 0, 2, 3. %q then shows a real newline and, separately, a backslash followed by n in the raw literal.

The last line shows that a variable can receive a new string, including the result of concatenation, while old retains the earlier value. You cannot change an individual byte of an existing string with text[0] = ...: string values are immutable. Replace ӘGo with Go and expect two bytes, two runes, and offsets 0 and 1. An empty string can be measured and ranged over, but indexing [0] panics; check len(text) > 0 first.

Before continuing, explain four expressions: "Ә", 'Ә', len("Ә"), and utf8.RuneCountInString("Ә"). They are respectively a string, a rune, two bytes, and one rune.

Observe the title rule

The checkpoint has main.go and title.go alongside go.mod, in the same package. go run . builds them together. Save the following as main.go:

package main
import (
    "fmt"
    "unicode/utf8"
)
func main() {
    title, ok := normalizeTitle("  Шаңырақ Go  ")
    if !ok {
        fmt.Println("Invalid title")
        return
    }
    fmt.Printf("Title: %q\n", title)
    fmt.Println("Bytes:", len(title))
    fmt.Println("Runes:", utf8.RuneCountInString(title))
    for offset, letter := range "ӘGo" {
        fmt.Printf("Byte %d: %c\n", offset, letter)
    }
}

Шаңырақ is a Kazakh word used here as an international Unicode example; you do not need to know Kazakh to follow it. It has seven letters, followed by a space and two Latin letters. Predict why byte and rune counts differ.

Save as title.go:

package main
import (
    "strings"
    "unicode"
    "unicode/utf8"
)
// normalizeTitle returns a single-line title without edge whitespace.
// The limit is in runes, not grapheme clusters or bytes.
func normalizeTitle(title string) (string, bool) {
    if !utf8.ValidString(title) {
        return "", false
    }
    title = strings.TrimSpace(title)
    if title == "" || utf8.RuneCountInString(title) > 80 {
        return "", false
    }
    for _, letter := range title {
        if unicode.IsControl(letter) || letter == '\u2028' || letter == '\u2029' {
            return "", false
        }
    }
    return title, true
}

Run go run .:

Title: "Шаңырақ Go"
Bytes: 17
Runes: 10
Byte 0: Ә
Byte 2: G
Byte 3: o

Both 17 and 10 are correct answers to different questions.

Bytes, runes, and what a reader sees

A byte holds eight bits. UTF-8 encodes Unicode code points as bytes. ASCII includes basic Latin letters, digits, punctuation, and controls; an ASCII character such as G takes one UTF-8 byte. Each of the seven letters in this example takes two bytes: fourteen, plus one for the space and two for Go gives seventeen.

A rune is an int32 alias used to represent a Unicode code point; utf8.RuneCountInString counts code points. A visible character may combine multiple code points, such as a letter and a separately encoded accent. Such sequences are grapheme clusters. Our limit of 80 runes is an explicit educational rule, not necessarily a limit of 80 visible characters.

range returns byte offsets and runes: ӘGo yields 0, 2, and 3. Indexing a string instead returns a byte; title[0] may be just one part of a multibyte character. An empty string has length zero and no element at index zero.

Why validate UTF-8?

Go source files are UTF-8, but a string obtained at runtime may contain arbitrary bytes, for example from a damaged file or another encoding. utf8.ValidString checks whether the bytes are valid UTF-8. Our rule rejects invalid input; it neither guesses an encoding nor presents replacement characters as the original title. Counting runes is a separate operation and does not itself prove the original bytes were valid.

Four steps of validation

Validate UTF-8, trim whitespace at both edges, require 1 to 80 runes, and reject control characters and Unicode line and paragraph separators.
Figure 6.1. Title validation — encoding, edge whitespace, length, and prohibited characters.

First validate UTF-8. Then strings.TrimSpace removes whitespace at both edges, preserving spaces between words. The trimmed title must not be empty or exceed 80 runes. Finally iterate over it and reject control characters, such as an internal newline. Explicitly reject U+2028 and U+2029 as well: unicode.IsControl checks the Unicode control category, while these line and paragraph separators belong to other categories.

Order matters. Whitespace and newlines alone become empty and are rejected. A trailing newline after Go is trimmed and the result Go is accepted. An internal newline in a multi-line title remains and is rejected.

This function does not perform full Unicode normalization or defend against every visually confusable character. Its name describes only the listed rules. Discuss normalization and comparison separately when search requires them, rather than silently changing an author's spelling.

Strings do not change internally

TrimSpace returns a string. Assigning it to the local title variable does not modify individual bytes of the supplied value. The caller receives the prepared string through return. Ignoring that result does not automatically trim the caller's original variable.

Test the boundary

The checkpoint's title_test.go checks 80 occurrences of Ә using strings.Repeat("Ә", 80). The first argument is the repeated string and the second is the count. It occupies 160 bytes but must pass an 80-rune limit. A following test adds one more and expects rejection.

Run go test ./... from the module root. Temporarily replace the rune count in the function with len(title) and rerun: the multibyte boundary test should fail. Restore the rune count and rerun. A short ASCII-only test would not expose this error because its byte and rune counts match.

Reading the notation

import (...) groups imports; its parentheses do not call a function. In for offset, letter := range text, the comma separates the two names; use _ to ignore one. %q displays a quoted escaped string and %c displays a rune as a character. The slash in the import path "unicode/utf8" is part of the path, not division.

In test strings, \t means a tab, \n a newline, and \xff inserts a byte using hexadecimal notation, allowing an intentionally invalid UTF-8 sequence. \u0301 represents a Unicode code point encoded as UTF-8 inside a string. '\u2028' and '\u2029' in single quotes are rune literals; "\u2028" in double quotes is a string. We compare letter to runes with ==, not to strings.

State the title limit fully: which units do we count, and what happens to edge whitespace?

Warm-up

Predict the byte and rune counts for Go and for Ә. Does the offset in range count bytes or runes? Which input reveals an 80-rune limit mistakenly implemented as len(title) <= 80?

Exercises

Required: add TestInternalSpaces. normalizeTitle(" Go дүкені ") should return "Go дүкені" and true. The word дүкені means “shop”; its language is not important to the rule. There are two internal spaces and the function must preserve them. Check both returned values.

Try a title in a language you know: predict rune count and compare it with the output. If it differs, check whether a visible character comprises multiple code points. Optional: compare "é" and "e\u0301" in byte lengths, rune counts, and ==. Do not remove the accent to force a match: that changes the data.

Answers

Go has two bytes and two runes; Ә has two bytes and one rune. range yields byte offsets. Eighty Ә characters reveal the len mistake: 80 runes but 160 bytes. The two forms of é occupy two and three bytes, contain one and two runes, and compare unequal as strings despite possibly appearing identical.

The shop now has a title rule. Next we will arrange several titles in an ordered catalog.

Part I · Junior · Build the storefront

CHAPTER 7 — The Catalog: Arrays, Slices, and Maps

Until now the program worked with one book. Now there will be several, and display order will be part of the result. We need three kinds of data: a fixed set of formats, a list of identifiers, and a map of titles. The SQL book below is an illustrative second catalog entry, not a promise that a second book exists for sale.

Checkpoint: examples/07-catalog. If building the files yourself, make a separate chapter folder with go.mod, new main.go and catalog.go, title.go and title_test.go carried over from chapter 6, and catalog_test.go from the companion checkpoint. The previous title validation remains in force. Create labs/01-arrays, labs/02-slices, and labs/03-maps under the root, each with its own main.go. Run commands from the folder containing go.mod. The working companion archive for chapters 2–7 contains the referenced tests.

A row of cards and a window

Lay three cards in a row and cover them with a sheet containing a window through which only two are visible. Moving the window's edge and rewriting a card are different actions. If two windows expose the same card, a change to it is visible through both.

A slice describes part of an underlying array. Copying a slice does not by itself create independent copies of the elements. Copying an array copies its elements. For independent slice storage, we will allocate space and explicitly copy data.

The analogy has a boundary: append may use space in the existing array or allocate another one, depending on capacity. Similar variable names do not establish independent storage. Draw two windows on one row, then a separate row for an independent copy. Predict which windows show a changed card.

Imagine a map as a separate set of “key–title” cards. It helps find a title by key but promises no display order. Our own list of keys supplies that order.

Three tasks, three experiments

Before combining the catalog, examine each container. You need types, for, range, functions, and the title rule. Structs and pointers arrive in the next chapter. Each lab is a separate program; do not replace the shop's main.go with a lab.

Array: a known number of elements

An index identifies a position starting at zero. For an array of length 3 the valid indexes are 0, 1, and 2. len returns the element count, not the last index. [3]string is a type; [3]string{"PDF", "EPUB", "HTML"} is a value written as a composite literal.

Save labs/01-arrays/main.go:

package main
import "fmt"
func main() {
    formats := [3]string{"PDF", "EPUB", "HTML"}
    other := formats
    other[0] = "TXT"
    fmt.Println(len(formats), formats[0], other[0])
    for index, format := range formats {
        fmt.Println(index, format)
    }
}

Run go run ./labs/01-arrays:

3 PDF TXT
0 PDF
1 EPUB
2 HTML

other := formats copies the three string elements. Changing other[0] does not replace formats[0]. For an array, range yields index and value; for a string, its first result was a byte offset. Array length has not grown: [3]string and [4]string are distinct types.

In a copy, try the constant index formats[3]: the compiler rejects it. An invalid index supplied at runtime causes a panic. A suitable check is 0 <= index && index < len(formats). Restore the working program before continuing.

Slices: length, capacity, and shared storage

[]string is a slice type. A slice describes a portion of an underlying array: its start, current length, and available capacity. Assigning a slice copies that description, not the underlying array. Two slices can reach the same elements, unlike the array-of-strings assignment above.

make([]string, length, capacity) creates a slice with those dimensions. If capacity is omitted it equals length. Length determines valid indexes now; capacity describes how far the slice can grow in the available array region. Capacity 3 with length 0 does not permit writing [0].

append returns an updated slice description: save the result. It uses the old array when capacity suffices and allocates another when necessary, so it does not guarantee an independent copy. copy transfers elements into an existing destination slice, returns how many it copied, and is limited by both slice lengths.

Save labs/02-slices/main.go:

package main
import "fmt"
func main() {
    titles := []string{"Go", "SQL"}
    same := titles
    same[0] = "Web"
    fmt.Println(titles[0])
    independent := make([]string, len(titles))
    copied := copy(independent, titles)
    independent[0] = "Other"
    fmt.Println(copied, titles[0], independent[0])
    empty := make([]string, 0, 3)
    fmt.Println(len(empty), cap(empty), copy(empty, titles))
    empty = append(empty, "Go")
    fmt.Println(len(empty), empty[0])
    base := [3]string{"Go", "SQL", "Web"}
    part := base[:1]
    grown := append(part, "New")
    fmt.Println(base[1], len(part), len(grown))
}

Run go run ./labs/02-slices:

Web
2 Web Other
0 3 0
1 Go
New 1 2

same[0] changes shared storage, visible through titles. independent has newly allocated storage and two copied elements; changing its first string leaves titles alone. empty has capacity 3 but length 0, so copy transfers zero elements. After saving append's result, its length is 1. base[:1] sees one element but can grow into the original array; append replaces base[1]. The old part still has length 1; grown has length 2.

In base[low:high], the lower boundary is inclusive and the upper boundary exclusive. An omitted low is zero; an omitted high is the current length. Extending a slice toward capacity requires bounds checking; it does not allow ordinary indexing beyond its length.

var titles []string creates a nil slice with length and capacity zero. You can append with titles = append(titles, "Go"). A separately created empty slice can have zero length without being nil. Neither has an element at index zero.

Try make([]string, 0, len(titles)) as the copy destination. Predict that copy returns 0 because the destination length is zero. Do not write its [0] until you fix its length; the exercise is about len, not catching a preventable panic.

Maps: presence matters more than position

map[string]int associates string keys with integer values. quantities["go"] = 2 creates or replaces an entry. A missing key returns the element type's zero value, here 0. To distinguish absence from a stored zero, use two results: value, exists := quantities["go"].

A map has no guaranteed first display element or iteration order. Keys must support equality comparison: strings do, slices do not. Reassigning the same key replaces its value rather than creating another entry.

Save labs/03-maps/main.go:

package main
import "fmt"
func main() {
    var uninitialized map[string]int
    fmt.Println(uninitialized["go"])
    quantities := make(map[string]int)
    quantities["go"] = 0
    value, exists := quantities["go"]
    missing, found := quantities["sql"]
    fmt.Println(value, exists, missing, found)
    quantities["go"] = 2
    same := quantities
    same["go"] = 3
    fmt.Println(quantities["go"])
    delete(quantities, "go")
    _, exists = quantities["go"]
    fmt.Println(exists, len(quantities))
    quantities["sql"] = 1
    clear(quantities)
    fmt.Println(len(quantities), quantities == nil)
}

Run go run ./labs/03-maps:

0
0 true 0 false
3
false 0
0 false

Reading a nil map is allowed; writing to it panics. make creates a usable map. Assigning same := quantities gives access to the same entries, so a write through same is visible through quantities. delete removes one key, doing nothing if absent. clear removes all entries but does not turn an initialized map into nil; it can still be written. Both are built-ins and return no value to assign.

Before the catalog, explain how two reads can both be zero while one presence flag is true and the other false. Choose a container for fixed formats, changing ordered IDs, and lookup by ID: in this experiment, an array, a slice, and a map respectively. This is not a mandatory design for every store.

The complete catalog

Save main.go in the root:

package main
import "fmt"
func main() {
    formats := [3]string{"PDF", "EPUB", "HTML"}
    fmt.Println("Formats:", formats)
    ids := []string{"go-shop"}
    ids = append(ids, "sql-notes")
    titles := map[string]string{
        "go-shop": "Go: From the First Line to an Online Bookstore",
        "sql-notes": "Notes on SQL",
    }
    ordered, ok := catalogTitles(ids, titles)
    if !ok {
        fmt.Println("Catalog incomplete")
        return
    }
    for index, title := range ordered {
        fmt.Println(index+1, title)
    }
    _, found := titles["missing"]
    fmt.Println("Unknown book found:", found)
}

Save catalog.go next to it; it calls normalizeTitle from chapter 6's title.go:

package main
// catalogTitles preserves ids order and rejects incomplete data.
func catalogTitles(ids []string, titles map[string]string) ([]string, bool) {
    ordered := make([]string, 0, len(ids))
    for _, id := range ids {
        title, ok := titles[id]
        if !ok {
            return nil, false
        }
        title, ok = normalizeTitle(title)
        if !ok {
            return nil, false
        }
        ordered = append(ordered, title)
    }
    return ordered, true
}

Run go run .:

Formats: [PDF EPUB HTML]
1 Go: From the First Line to an Online Bookstore
2 Notes on SQL
Unknown book found: false

The map finds titles by ID; the slice sets their display order.

Arrays: length is part of the type

[3]string is an array of exactly three strings; [2]string is a different type. We use indexes 0 through 2. The array demonstrates a fixed set, not an architectural requirement that formats must forever be stored this way. Books with different files may require a different model.

Assigning an array copies its elements. Replacing a string in the copied array does not replace the original element. If elements themselves refer to shared data, copying the outer array does not automatically make that data independent.

Slices: the visible part of an array

[]string has no length between the brackets. append(ids, "sql-notes") returns a slice with the added element, and we save it back in ids. The slice describes a start, length, and available capacity; adding changes length and may require another array. Without the returned value you do not have the correct description of the extended slice.

len gives visible elements now. cap gives available elements from this slice's start to the end of its accessible array region; for a slice starting in the middle, it need not equal the entire array length. make([]string, 0, len(ids)) makes an empty destination with enough capacity for our output. ordered[0] is invalid until an element has been added.

Slices ids and part both refer to the go-shop element of one underlying array; ids also includes sql-notes. Changing part[0] changes the element observed at ids[0].
Figure 7.1. Two slices can refer to the same array element.

part := ids[:1] is a window, not an independent copy. The lower bound defaults to zero and the upper bound is excluded, so only index 0 is visible. A change to part[0] is visible through ids[0]. To copy a list of strings independently, allocate a destination with the needed length and use copy. It copies up to the shorter length and reports the count; a zero-length destination copies nothing even if capacity is large. A slice of structs containing maps or slices can still share nested data. Do not rely on a specific capacity growth factor after append; check the behavior and independence your program requires.

Map: a key instead of a position

In map[string]string, the first type is the key and the second the value. title, ok := titles[id] returns the value and a presence flag. An absent key produces an empty string and false; a present key storing an empty string produces true. catalogTitles first checks presence, then calls normalizeTitle from chapter 6, which verifies UTF-8, trims edges, limits rune count, and enforces one line. The output receives the prepared title.

A map's zero value is nil. Reads return absent entries, but writes panic until the map is initialized with make or a literal. This depends on the value, not the keyword var: var titles = make(map[string]string) is usable. Assigning a map to another variable does not create independent storage; changes through either name are visible through the other.

Why the display does not range over the map

Map iteration order is unspecified. A few convenient runs do not make that order reliable. Instead, range over ids and look up each title. If data is missing or invalid, return nil, false instead of presenting a partial catalog as complete.

Two containers must remain consistent: adding an ID without a title is possible. We deliberately expose this risk; the next chapter combines a book's fields into a struct. A map helps key lookup, but a metaphor of instantaneous retrieval is not a guarantee of zero time or identical costs. Measure performance on the actual task and data.

Checking behavior

catalog_test.go checks order, a missing key, an empty title, and an empty catalog. Run go test ./.... An empty catalog is allowed: an empty result with success true. A promised ID with no title is an error. Both may show no lines, but their meanings differ.

Reading the notation

[3]string is a three-string array; []string is a slice. Values in braces after a type form a composite literal. [0] indexes an element; [:1] selects from the start up to but excluding 1. map[string]string maps string keys to string values; the colon in a literal separates a key from its value. make, append, copy, len, and cap are built-ins and require no import. nil is a zero value for slices, maps, and some other types, not for an integer or string.

A multiline composite literal also has a comma after its last element before the closing brace. This explanation concerns that particular multiline form, not every one-line argument list. range ordered gives an index and value. index+1 changes only the printed numbering; the slice still starts at index zero. %v in test messages shows a value in its default format.

Draw the key–title cards and a separate list of display keys. Trace the first key to its title. If you reach for “the first map entry,” return to the unspecified-order rule.

Warm-up

How many elements are visible after make([]string, 0, 10)? Fill in ids = ___(ids, "new-book"). If copy returned zero despite destination capacity 10, which other destination property should you inspect?

Exercises

Required: add a third ID, go-tests, with title Go Testing. It must appear third. Then remove only its title from the map: the program must report Catalog incomplete, not show the first two as if the whole catalog succeeded.

Try your own data: reorder IDs and verify that display order changes without rewriting map pairs. Optional: take part := original[:1] from a two-string slice and change part[0]. Repeat with an independent destination and copy; compare the results.

Answers

Length is zero; capacity does not permit indexing an element that is not yet present. Use append and save its result. copy depends on destination length. The required exercise changes two places: the ID list and map entry. A struct will combine fields for one book, although a full catalog still needs ordering and lookup.

We now have an ordered catalog that rejects incomplete data. Next we will combine identifier, title, price, and publication state into one value.

Part I · Junior · Build the storefront

CHAPTER 8 — A Book as a Value: Structs, Methods, and Pointers

A title, price, and publication flag belong to one book. Separate variables or parallel maps make it easy to mix up which value belongs where. We will combine the data while keeping the rules already written.

Checkpoint: examples/08-books. pricing.go contains chapter 5's discount rule and title.go chapter 6's title validation. Their behavior remains unchanged and is checked by the same tests.

If typing the project yourself, create a new folder with go.mod, main.go, book.go, pricing.go, title.go, and the tests book_test.go, pricing_test.go, and title_test.go. The prepared checkpoint contains these files. From chapter 5 copy only the pricing function and tests, renamed here to pricing_test.go—not a second main function. Chapter 7's map remains a learning experiment; this example shows one Book, not yet a full catalog of structs.

A book card and a written address

A card contains a book's title, price, and publication mark. Copy the card and change the copy's title: the first card retains its text. This is a useful starting point for copying our current Book struct.

Now copy the card's address onto another piece of paper. Two papers hold an address, but there is still one card. If someone follows either address and marks the card published, both addresses lead to that change. Copying a pointer copies its address value; it does not create another book.

A copy of the card is another card; a copy of the address leads to the original card. A method with a pointer receiver can modify the original book. If a struct later contains slices or maps, however, copies can share internal data, so the two-independent-cards picture needs qualification. Draw two address slips pointing to one book and explain what pointer assignment copies.

Three small experiments first

Do not learn a struct, an address, and a new form of function call all at once. The checkpoint contains three independent labs. Run each from the 08-books module root, next to go.mod. If typing them yourself, create each named labs directory and save its listing as main.go there. Do not replace the shop's main.go.

A struct without pointers or methods

type Book struct { ... } defines a type with named fields. Book{Title: "Go", PriceMinor: 150} creates a value; a colon connects a field name to its initial value. Omitted fields receive zero values. The dot in original.Title selects a field, not a package function.

package main
import "fmt"
type Book struct {
    Title string
    PriceMinor int64
    Published bool
}
func main() {
    original := Book{Title: "Go", PriceMinor: 150}
    copied := original
    copied.Title = "SQL"
    fmt.Println(original.Title, copied.Title, original.Published)
    var empty Book
    fmt.Printf("[%s] %d %t\n", empty.Title, empty.PriceMinor, empty.Published)
}

Run go run ./labs/01-structs:

Go SQL false
[] 0 false

copied := original copies every field. Replacing copied.Title does not change original.Title. empty is an existing struct value with zero-valued fields, not an absent book. Set Published: true in original's literal and predict what the copy receives: the state at the time of assignment, not at a later print.

An address separate from the card

In *int, the star denotes a pointer to an integer. &quantity obtains a variable's address; *address accesses the variable at that address. Assigning *address = 9 changes that variable. The same star in 2 * 9 is multiplication.

package main
import "fmt"
func replaceCopy(value int) { value = 9 }
func replaceThroughAddress(address *int) { *address = 9 }
func main() {
    quantity := 2
    replaceCopy(quantity)
    fmt.Println(quantity)
    address := &quantity
    sameAddress := address
    replaceThroughAddress(sameAddress)
    fmt.Println(quantity, *address, address == sameAddress)
    var absent *int
    fmt.Println(absent == nil)
}

Run go run ./labs/02-pointers:

2
9 9 true
true

The first call changes only its parameter, leaving quantity at 2. The second also receives a copy of its argument, but that argument is quantity's address. Following the copied address changes the original integer. address == sameAddress compares pointers, not two independently created numbers.

A nil pointer has no address. It can be compared with nil, but reading or writing *absent panics. Modifying through a pointer requires an existing value and a clear agreement about who can modify it. It is not automatic protection against errors, and this program does not require a separate manual memory-release operation.

Try creating another integer with value 9 and comparing its address with address. The result is false: equal contents do not make two variables the same object.

A method adds a receiver, not a new argument-passing rule

An ordinary function has arguments after its name. A method additionally declares a receiver before its name: (book Book) or (book *Book). book.Publish() supplies that object as the receiver. To declare a method for a type, the type must be defined in our package.

package main
import "fmt"
type Book struct {
    Title string
    Published bool
}
func (book Book) RenameCopy(title string) { book.Title = title }
func (book *Book) Publish() bool {
    if book == nil { return false }
    book.Published = true
    return true
}
func main() {
    book := Book{Title: "Go"}
    book.RenameCopy("SQL")
    fmt.Println(book.Title)
    fmt.Println(book.Publish(), book.Published)
    var absent *Book
    fmt.Println(absent.Publish())
    books := []Book{{Title: "Go"}, {Title: "SQL"}}
    for _, copy := range books { copy.Publish() }
    fmt.Println(books[0].Published, books[1].Published)
    for i := range books { books[i].Publish() }
    fmt.Println(books[0].Published, books[1].Published)
}

Run go run ./labs/03-methods:

Go
true true
false
false false
true true

RenameCopy modifies a struct copy, so the title is still Go. Publish receives a pointer. For an addressable variable here, book.Publish() is equivalent to (&book).Publish(), so the change persists. Our nil receiver returns false because we explicitly check it, not because Go makes every method safe automatically.

The last two loops contrast copies of slice elements with the elements themselves. In the first, copy is a new struct variable; in the second, books[i] identifies the actual element. Remove one loop at a time, predict the other's result, and run it. Do not make every receiver a pointer at random: first decide whose state must change.

Before moving on, explain copying a struct, copying a pointer, and changing a value through a pointer. Then write an Unpublish pointer method with clear nil behavior: keep the nil check and set the field to false. Now connect the concepts to title and price validation.

A working book

Save book.go:

package main
type Book struct {
    ID string
    Title string
    PriceMinor int64
    Currency string
    Published bool
}
// PriceAfterDiscount calculates a price without changing the book.
func (b Book) PriceAfterDiscount(percent int64) (int64, bool) {
    return priceAfterDiscount(b.PriceMinor, percent)
}
// Publish changes the book only after all checks succeed.
func (b *Book) Publish() bool {
    if b == nil || b.ID == "" || b.Currency != "KZT" { return false }
    title, ok := normalizeTitle(b.Title)
    if !ok { return false }
    _, ok = priceAfterDiscount(b.PriceMinor, 0)
    if !ok { return false }
    b.Title = title
    b.Published = true
    return true
}

Save main.go:

package main
import "fmt"
func main() {
    book := Book{
        ID: "go-shop",
        Title: "  Go: From the First Line to an Online Bookstore  ",
        PriceMinor: 249900,
        Currency: "KZT",
    }
    fmt.Println("Before publication:", book.Published)
    if !book.Publish() {
        fmt.Println("Book is not ready for publication")
        return
    }
    fmt.Println("After publication:", book.Published)
    price, ok := book.PriceAfterDiscount(10)
    if !ok {
        fmt.Println("Invalid discount")
        return
    }
    fmt.Println(book.Title)
    fmt.Println("Amount due:", price, "minor units of", book.Currency)
}

Bring title.go and the priceAfterDiscount function in pricing.go from earlier checkpoints. The prepared chapter already contains them. Do not copy another main.go: the package needs one main function. From the root run go run .:

Before publication: false
After publication: true
Go: From the First Line to an Online Bookstore
Amount due: 224910 minor units of KZT

Publication changed, edge whitespace was trimmed, and the calculated price uses the earlier discount rule. We combined checked parts rather than rewriting the shop.

Structs connect fields

Book lists named, typed fields. The main function creates one value with a keyed composite literal. Published is omitted and receives its zero value, false: this agrees with our rule that a new book begins as a draft. book.Title selects a field of a specific value. Different Book variables can contain different titles and prices; the type defines a shape, not a single global book.

Capitalized field names are exported from the package. Everything is still in main in this chapter; package boundaries come later. Exporting a field does not prevent an invalid assignment such as a negative price, so publication validation remains necessary.

A method is a function with a receiver

(b Book) before PriceAfterDiscount is its receiver. book.PriceAfterDiscount(10) supplies the book and the percentage. A value receiver gets a copy of Book: in our current struct, strings, integer, and Boolean fields are copied. The method forwards the price to the existing function and changes nothing. It is a way to connect an action with data, not a new arithmetic rule. Ordinary functions can be clearer when a method adds no useful connection.

A pointer tells us where to write

Publish has receiver (b *Book): a pointer to a Book. Go passes arguments by value, including pointers. The copied pointer still refers to the same book; “there is no copying when there is a star” is false.

&book obtains the variable's address; *pointer accesses the value there. Go permits pointer.Title as shorthand for (*pointer).Title. The compiler can take the address automatically in book.Publish() for an addressable value. Not every temporary expression is addressable; save a returned value in a variable before attempting such a modification when necessary.

A pointer's zero value is nil. Our Publish first checks b == nil, returning false without reading a field of an absent book. Calling a method on a nil pointer is not automatically safe: it depends on the method's code. PriceAfterDiscount has a value receiver and does not accept an absent Book as a valid value.

Change only after all checks

Publish checks the pointer, ID, and currency, then stores the normalized title in a local variable and checks price using a zero discount. Only after all checks succeed does it write Title and Published. If the price is invalid, even trimmed whitespace is not saved. TestInvalidBookUnchanged compares the book with its earlier state.

This illustrates a useful rule: failure should not leave a partial change when the operation promises all-or-nothing behavior. A database will later require a transaction; here the order of assignments inside one function is enough.

The loop trap: changing a copy

In for _, book := range books, book receives each element's value. For []Book it is a struct copy; book.Publish() changes that copy, leaving the slice element a draft. To change elements, iterate by index: for i := range books and call books[i].Publish(). The element is addressable.

book_test.go checks both behaviors: changing a copy leaves the original unchanged, then changing the slice element persists. Reproduce both rather than guessing from the code's appearance.

What if a field is a map or slice?

Pointers p and q refer to the same Book; changing Published through either pointer changes the shared book.
Figure 8.1. Copying a pointer keeps access to the same book.

Our Book has simple fields for now. If it gains a map or slice, copying the outer struct may preserve access to shared internal data. Changing an element of such a container differs from replacing the field itself. If a and b are copies with Titles map[string]string, b.Titles["go"] = "New" changes the shared map. b.Titles = make(map[string]string) replaces only b's field. The source package includes a separate reproduction under book/research/reproductions/map-value.

Do not justify a receiver with “pointers are always faster.” First decide the semantics: should the change persist, is there shared state, and may the type be copied? Performance measurements are a separate task.

Reading the notation

type declares a type; struct { ... } lists fields. In Book{ID: "go-shop"}, braces form a composite value and the colon connects a field to its value; struct declarations use a field name and type without a colon. book.Title selects a field; book.Publish() selects and calls a method. (b Book) declares a value receiver; *Book denotes a pointer receiver. &book obtains an address; *pointer dereferences it. In a test's %+v, + asks fmt to include struct field names; it is not arithmetic.

Our test can compare book != before because all current Book fields are comparable. Add a slice or map and the struct is no longer comparable with that operator: the test must change with the data shape.

Read one book literal and one method call aloud, explaining the different brackets and the object modified by the pointer receiver.

Warm-up

Predict: after copy := book and copy.Title = "Another book", does the current book.Title change? Which symbol obtains an address, & or *? If a range loop calls Publish on copies while books remains drafts, which loop should change the actual elements?

Exercises

Required: write a test for a free book with nonempty ID and Title, KZT currency, and zero price. Publish must return true and set Published; this agrees with chapter 5's valid zero price. Check both the return and state.

Try your own data: create two books in a slice, publish by index, and print published titles. Make one price invalid and verify that this book remains a draft. Optional: add Unpublish, define repeated-call behavior, and test it. Withdrawing a title from display must not automatically delete files already purchased.

Answers

Changing the copied string field does not replace the original's field. & obtains an address. Iterate indexes and use books[i] to modify elements. A free-book test must check both method result and field; true alone could conceal a method that changed nothing.

We have a book model that connects the title and price rules. Next we will return an informative error when a file operation fails. Publish still returns bool; not every interface changes simultaneously.

Part I · Junior · Build the storefront

CHAPTER 9 — A File Did Not Open: Errors and Releasing Resources

The book title currently lives in source code. Correcting a typo requires changing the program. We will move the title into title.txt while retaining its validation. After a successful read, the book goes through the same Publish method as in chapter 8.

Checkpoint: examples/09-errors. You need functions, multiple return values, structs, and pointers. This chapter introduces error values, deferred calls, and a small reading contract before the exercises.

If typing yourself, copy the chapter 8 folder. Replace main.go with this chapter's listing; add file.go, file_test.go, and defer_test.go from the checkpoint, plus a plain UTF-8 text file title.txt without a byte-order mark (BOM). Keep the other Go files and go.mod. Ensure the extension is .txt, not .txt.txt. Run the terminal in this folder: the relative title path is resolved from the current directory. A BOM is an optional encoding marker at a file's beginning; select ordinary UTF-8 without BOM so the marker does not become part of the title.

A key and a note by the door

Imagine a reading room. You receive a locker key, retrieve a page, and leave. Even with the page in hand, you must return the key. If the locker opens but the page is missing, the key must still be returned. If no key was issued, there is nothing to return.

An opened file similarly needs its resource released. An error check asks whether we obtained the key. defer lets us immediately leave a note: “Before leaving, return it.” An early return for an invalid title will still attempt the close. The metaphor is not an operating-system specification; closing a file does not itself guarantee all data has reached physical storage. We are reading here; durable writes come later.

First: functions as values, errors, and defer

Test the new mechanisms before combining them with file access. Run commands from the 09-errors module root. Each labs directory contains a separate main package.

Passing a function does not call it

In operation := twice, the name appears without (), so the function is saved. In operation(3), parentheses call it. The type func(int) int describes one int parameter and one int result; the parameter name is optional. apply receives such a function and calls it later. This is a basis for callbacks used by HTTP handlers.

Save labs/01-functions/main.go:

package main
import "fmt"
func twice(value int) int { return value * 2 }
func apply(value int, operation func(int) int) int { return operation(value) }
func main() {
    operation := twice
    fmt.Println(operation(3), apply(4, operation))
    increment := 1
    next := func(value int) int { return value + increment }
    fmt.Println(next(3))
    increment = 5
    fmt.Println(next(3))
}

go run ./labs/01-functions prints:

6 8
4
8

The anonymous function uses increment from its enclosing block: it is a closure. After increment becomes 5, the next call sees 5. The closure retains access to the variable; it does not permanently capture the earlier number. Try saved := increment before creating the function and use saved inside it: the second call also returns 4 because saved was not changed.

An error is a value with behavior

error is a predefined interface with the method Error() string. An interface specifies available behavior; a concrete type provides an implementation. You need not design a large interface architecture to use the contract. Our small type shows where the method comes from.

Save labs/03-errors/main.go:

package main
import (
    "errors"
    "fmt"
)
type titleError struct{ reason string }
func (problem titleError) Error() string { return problem.reason }
func main() {
    var absent error
    fmt.Println(absent == nil)
    var problem error = titleError{reason: "empty title"}
    fmt.Println(problem.Error())
    cause := errors.New("missing file")
    wrapped := fmt.Errorf("read title: %w", cause)
    fmt.Println(wrapped)
    fmt.Println(errors.Is(wrapped, cause))
    fmt.Println(errors.Is(wrapped, errors.New("missing file")))
}

go run ./labs/03-errors prints:

true
empty title
read title: missing file
true
false

titleError is a struct and Error is its method. Its value can therefore be assigned to error; Go has no separate implements keyword. The caller uses the interface's method without reading reason. The zero interface variable absent contains no concrete value and equals nil. Chapter 18 explains the distinct case of an interface containing a nil pointer; do not confuse that with an ordinary return nil.

fmt.Errorf with %w adds context and preserves the cause. errors.Is checks the error chain, not matching message text. Separate errors.New calls create distinct errors even if their messages match, so the final check is false. Replace %w with %v: the message looks similar but the cause is no longer wrapped and the first errors.Is becomes false. Restore %w.

What defer actually defers

defer schedules a call for the end of the current function. Arguments of an ordinary deferred call are evaluated immediately; the call executes later. Multiple deferred calls run in reverse registration order. A deferred closure can read a variable after it changes.

Save labs/02-defer/main.go:

package main
import "fmt"
func observe() {
    value := 1
    defer fmt.Println("argument", value)
    defer func() { fmt.Println("closure", value) }()
    value = 2
    fmt.Println("body", value)
}
func result() (value int) {
    defer func() { value = value + 1 }()
    return 10
}
func main() {
    observe()
    fmt.Println("result", result())
}

go run ./labs/02-defer prints:

body 2
closure 2
argument 1
result 11

The body prints first. The closure then reads the new value 2; the last call prints argument 1, evaluated at registration. The final () after the anonymous function denotes the deferred call; without it there would only be a function value.

In result() (value int), the result is named and behaves as a function variable. return 10 assigns it 10, defer increases it to 11, and only then does the caller receive it. This mechanism lets us preserve a close error. Swap the two deferred calls in observe and predict the output before running. Explain why the ordinary argument remains 1; if you cannot, repeat the small experiment before reading the longer file code.

The intended result

The checkpoint retains Book, discount and title rules, and their tests. Add title.txt containing the following line, including two leading spaces:

  Go: From the First Line to an Online Bookstore

After go run ., the intended output is:

Go: From the First Line to an Online Bookstore
Published: true

The file supplies only the title. We leave price and currency in code to avoid introducing a custom catalog format at the same time. This is an intermediate step, not finished shop storage.

Save main.go:

package main
import (
    "errors"
    "fmt"
    "os"
)
func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
func run() error {
    title, err := loadTitle("title.txt")
    if err != nil { return err }
    book := Book{ID: "go-shop", Title: title, PriceMinor: 249900, Currency: "KZT"}
    if !book.Publish() { return errors.New("book did not pass validation") }
    fmt.Println(book.Title)
    fmt.Println("Published:", book.Published)
    return nil
}

run reads the title, creates a card, and calls the existing Publish method. Output occurs only after validation; an error does not become an empty published book.

What changed from bool?

Earlier, a second result reported true or false. Now we want to distinguish a missing file, a read failure, and an invalid title. A function returns error for this purpose. For the ordinary cases used here, nil means no error and a non-nil value indicates failure. errors.New creates an error with a message. return nil in run is successful completion, not a print. A function returning (string, error) can use return title, nil on success and return "", err on failure.

Do not infer failure from an empty string alone: inspect the returned error. Our functions deliberately clear their string result on failure; not all standard-library functions promise the same contract.

Where to decide what an error means

main calls run. In if err := run(); err != nil, the initialization comes first and the condition after the explicit semicolon. err is scoped to that if. fmt.Fprintln(os.Stderr, err) writes diagnostics to standard error, separate from standard output. os.Exit(1) ends the process with a nonzero exit code; returning successfully from main gives zero. A return from an ordinary function does not by itself set the process exit code.

os.Exit does not run deferred calls. File work therefore occurs inside a deeper reading function and finishes before the error reaches main. By the time main calls os.Exit, our reading function has already attempted to close any opened resource.

Three passes, not one giant jump

First trace run: call, err check, early return, successful nil. Then inspect the defer tests: no files or reading interfaces are involved. Only then move to file.go, where the mechanisms work together.

The checkpoint's defer_test.go tests three observations. TestDeferOrder registers closures that append digits 1 and 2 to a value: reverse execution produces 21. TestDeferArgumentAndClosure registers an ordinary argument with n = 1 and a closure that reads n after it becomes 2: the results are 1 and 2. TestDeferNamedResult returns nil from a function with a named err result, then a deferred closure assigns a saved close error; errors.Is recognizes it. Run go test -run TestDefer -v .. The flag -run selects names and -v shows test names and results. Read the complete file from the checkpoint and predict results before running.

f := func() { ... } saves a function; f() calls it. func() (err error) has no inputs and one named result. Explain all three observations before proceeding: memorizing the longer file will not substitute for understanding their order.

Open the file and preserve failure causes

Save file.go:

package main
import (
    "errors"
    "fmt"
    "io"
    "os"
)
const maxTitleFileBytes = 1024
var ErrTitleTooLarge = errors.New("title file is too large")
var ErrInvalidTitle = errors.New("invalid book title")
func loadTitle(path string) (string, error) {
    file, err := os.Open(path)
    if err != nil {
        return "", fmt.Errorf("open title %q: %w", path, err)
    }
    title, err := readTitleAndClose(file)
    if err != nil {
        return "", fmt.Errorf("read title %q: %w", path, err)
    }
    return title, nil
}
// readTitleAndClose takes responsibility for closing reader.
func readTitleAndClose(reader io.ReadCloser) (title string, err error) {
    defer func() {
        closeErr := reader.Close()
        if closeErr != nil {
            title = ""
            err = errors.Join(err, closeErr)
        }
    }()
    data, err := io.ReadAll(io.LimitReader(reader, maxTitleFileBytes+1))
    if err != nil { return "", err }
    if len(data) > maxTitleFileBytes { return "", ErrTitleTooLarge }
    title, ok := normalizeTitle(string(data))
    if !ok { return "", ErrInvalidTitle }
    return title, nil
}

os.Open opens an existing file for reading and returns *os.File and an error. On error, return immediately; only a successful open supplies a file to readTitleAndClose.

fmt.Errorf with %q includes a quoted path and %w wraps the original error. %v could print the cause but would not create the same error-chain relationship. Check errors.Is(err, fs.ErrNotExist) when the program needs to recognize a missing file; do not compare err.Error() to a particular operating-system message, which can vary across platforms and contexts.

ErrTitleTooLarge and ErrInvalidTitle are package variables created once as recognizable causes. A fresh errors.New with the same text is a different error. Tests compare against the declared values. Here the program author chooses title.txt in the current directory; this is not an internet download path. Accepting a user-supplied path would require a separate contract for allowed files and directory boundaries.

Why separate reading?

readTitleAndClose accepts io.ReadCloser: a value providing Read and Close methods. A real file satisfies the interface. Tests can supply a small object with the same methods to deliberately produce failures. There is no implements keyword. In Read(p []byte) (int, error), the caller supplies a slice to fill; Read returns a byte count and error. io.ReadAll repeats reading and collects the result.

The function expects a valid open resource; passing nil cannot provide usable Read and Close operations. This first interface example addresses a concrete question: can both read and close failures be preserved? Reliably triggering both on a real disk across three operating systems is inconvenient.

The function name and comment define ownership: once passed in, readTitleAndClose is responsible for closing it. loadTitle therefore does not call Close a second time. Without an ownership rule, multiple functions can accidentally close twice or forget to close.

The defer note: what happens when?

In (title string, err error), named result variables start at their zero values: empty string and nil. A deferred closure can update those results if closing fails.

defer func() { ... }() creates an anonymous function, calls it with the final (), and defers that call until the surrounding function exits. The closure accesses reader, title, and err from the enclosing function; it changes the named results.

With return title, nil, Go first assigns the return values to result variables, then runs defer, then returns to the caller. A failed close can therefore replace nil with an error. In data, err := ..., data is new in the same block, so err is assigned rather than redeclared. Likewise in title, ok := ..., ok is new and title remains the named result. At least one name must be new for a short declaration in the same block. A declaration inside a nested block could shadow an outer variable, so read the brace boundaries carefully. Explicit return values make the main path visible.

On a close error, clear title and use errors.Join(err, closeErr). It combines non-nil errors so errors.Is can recognize each cause. A read failure is not lost; a successful read followed by failed close still returns an error. This function's strict contract treats success as both a successful read and a successful close.

Multiple deferred calls run in reverse order; arguments of an ordinary deferred call are evaluated immediately, while a closure can read variables later. Do not register defer inside a long loop expecting it to release each file at the end of each iteration: defer waits for the surrounding function to return. A small function handling one file provides a useful boundary.

Limit what we read

A title must not require loading an enormous file. io.LimitReader(reader, maxTitleFileBytes+1) limits the stream; io.ReadAll collects the bytes into []byte. This limits bytes read, does not check the file size in advance, and does not close the resource.

Why +1? Reading only 1024 bytes would not distinguish a 1024-byte file from the start of a longer one. Reading at most 1025 lets us detect excess without loading the remaining megabytes.

len(data) counts bytes. string(data) converts them to a string, then normalizeTitle validates UTF-8, trims edge whitespace, and checks the title. The 1024-byte input limit and 80-rune title limit answer different questions. A huge file containing only spaces is rejected before normalization. If reading fails after returning some bytes, our function discards them rather than publishing a truncated title. An ordinary end of stream is not itself an io.ReadAll error.

Notation in the tests

[]byte("Go") converts a string to a byte slice. 0o600 is an octal integer passed to os.WriteFile as test-file permissions; their interpretation varies by operating system and is not a configuration for the future server. t.TempDir() creates a temporary directory cleaned up by the test framework. filepath.Join combines path components according to the OS. t.Run starts a named subtest and accepts an anonymous function with *testing.T.

[]struct { ... } is a slice of values of an unnamed struct type. Fields represent inputs and expected results; each row supplies values in field order. 0xff is hexadecimal and can construct invalid UTF-8.

In the test's trackedReader, the reader field is an io.Reader. Its Read(p []byte) (int, error) delegates reading. Close increments a counter and returns the error chosen by the test. The test can therefore observe closing without guessing from a message. failingReader uses struct{}, an empty struct: it needs no data to return its test error each time.

After opening the file, register a deferred close, then read. Both success and failure reach Close before the function returns; error causes remain visible.
Figure 9.1. an opened resource is closed before return on success or failure.

Verify the function's promises

Run go test ./.... The checkpoint tests real file reading, preservation of the missing-file cause, empty titles, invalid UTF-8, multiple lines, the exact input-size boundary, and one byte beyond it. It separately checks a close failure and simultaneous read and close failures. Each resource test expects exactly one Close.

Start with TestMissingTitleKeepsCause in file_test.go: the wrapper adds context but errors.Is still recognizes a missing file. Then inspect TestReadAndCloseErrorsBothSurvive: one error must not hide the other.

Exercises and a memory map

Required: add a test in which an empty invalid title and Close both fail. Expect an empty result, both causes recognized with errors.Is, and exactly one close. Write those four conditions in words first.

Hint: construct trackedReader with strings.NewReader("") and a saved closeErr. Do not call errors.New again when comparing: retain the same error value. Check got == "", errors.Is(err, ErrInvalidTitle), errors.Is(err, closeErr), and reader.closes == 1. If the first cause disappears, check that the close error was joined rather than simply replacing err.

Predict: in a small function register defer fmt.Println("first"), then defer fmt.Println("second"), then print "work" normally. The output is work, second, first.

Compare: with n := 1, defer fmt.Println(n), then n = 2, the deferred call prints 1 because the argument was evaluated at registration. defer func() { fmt.Println(n) }() instead prints 2 because the closure reads the variable when executed.

Test failure in your own checkpoint copy: temporarily rename title.txt, run the program, and restore its name. The diagnostic includes context for opening the file; OS-specific details need not match the book word for word.

Draw: obtain resource → register close → read → validate → return. Add two paths toward close, one for success and one for failure. Explain why both reach the same action.

The shop now has its first external content. We can bound the input, explain failure, and release a resource. Next we will organize the code into packages while keeping its rules visible and testable. References: Go's errors, io, and os packages, and defer in the Go specification.

Part I · Junior · Build the storefront

CHAPTER 10 — Packages: An Address for Each Rule

By the end of this chapter the program still reads a title and publishes a book. The source organization changes: catalog rules can be used from the terminal and later from an HTTP handler. You will locate a definition through an import, run all tests, and explain why a module is not the same as a repository.

Before starting, reconstruct chapter 9's sequence without hints: open → limit reading → validate title → close → return the error cause. If it is unclear why a read failure must still lead to a close, repeat the three defer tests first.

Checkpoint and transition

Open examples/10-packages from the companion code. It already contains go.mod; do not run go mod init again. Each chapter folder is an independent shop version, not a subdirectory in one giant module. Keep the terminal at the checkpoint root containing go.mod and title.txt. The entry point is now cmd/shop/main.go:

10-packages/
  go.mod
  cmd/shop/main.go
  title.txt
  stdout.txt
  internal/
    catalog/
      book.go          book_test.go
      pricing.go       pricing_test.go
      title.go         title_test.go
    titlefile/
      file.go          file_test.go

For a manual transition, copy chapter 9 to a new folder. Move book, pricing, and title files with their tests into internal/catalog; change their package line to package catalog. Rename normalizeTitle to NormalizeTitle in those files. Move file.go and file_test.go to internal/titlefile, set package titlefile, and rename loadTitle to Load. Import catalog in file.go and call catalog.NormalizeTitle. The educational defer_test.go remains useful in chapter 9 but is not part of the catalog package. Create cmd/shop, move main.go there, and retain package main. Do not leave old copies of moved files in the new root.

The prepared go.mod identifies the module by a path such as:

module github.com/dake-edu/gopher-shop/book/examples/10-packages

go 1.27.1

The go directive is a minimum required version, not proof of the installed toolchain version. The English examples in this working edition target the tested Go 1.27.3 toolchain; use go version to inspect yours. The module path names a namespace, not a command to download the project. Go finds the module's own packages within it. If you create a separate product, choose your own module path and change the imports consistently.

Package, module, repository

A package groups Go files in one directory; their declarations are available to one another without imports. Tests can belong to the same package; an external test package ending in _test comes later. A normal package directory cannot mix package main and package catalog.

A module is a tree of packages with go.mod at its root and its own version requirements and dependencies. A repository stores file history. One repository can contain several modules, as our independent checkpoints do. go test ./... from one chapter does not cross into neighboring modules.

For a memory aid: a package is a department, a module an organization, and a repository an archive of changes. The analogy has limits: not every filesystem directory is a Go package, and Git does not run the program.

internal has a special import rule: a package inside an internal directory may be imported only by code within the tree rooted at internal's parent. Our shop packages can import internal/catalog; an unrelated module outside that tree cannot. This is a tool-enforced architectural boundary, not protection against reading secret files.

Two packages before moving the shop

The checkpoint includes labs/01-package/main.go and labs/01-package/greeting/message.go. The chapter root's go.mod is shared. greeting is a separate package; the lab's main.go belongs to package main.

File labs/01-package/greeting/message.go:

package greeting
func Message(title string) string { return "Book: " + title }

File labs/01-package/main.go:

package main
import (
    "fmt"
    "github.com/dake-edu/gopher-shop/book/examples/10-packages/labs/01-package/greeting"
)
func main() { fmt.Println(greeting.Message("Go")) }

From the chapter root, go run ./labs/01-package prints:

Book: Go

The import path combines the module path with the folder's relative path labs/01-package/greeting. This package belongs to the current module; the command should not need to download it from GitHub. In your own module replace the prefix with your go.mod module path while retaining the folder suffix. The name greeting used in the call comes from package greeting, not the filename message.go.

In a copy, rename Message to lowercase message but leave the call from the other package: the compiler cannot access the expected exported name. Restore Message. Then remove the import while leaving the call: the missing package name is a different failure. Restore the import. Do not move this teaching package into internal/catalog; it illustrates imports rather than shop rules. The labs do not change the app's entry point.

Export and dependency direction

Names beginning with an uppercase letter are exported: Book, Publish, NormalizeTitle, and Load. A lowercase name is available within its package only. Do not export every helper; readTitleAndClose remains a file-reading detail.

Current dependencies:

main → titlefile → catalog
main → catalog

The catalog knows nothing about files, so an HTTP layer can reuse its rules later. A cycle such as catalog → titlefile → catalog is forbidden; Go reports import cycle not allowed. Fix the ownership of the rule rather than moving imports at random.

Complete cmd/shop/main.go:

package main
import (
    "fmt"
    "os"
    "github.com/dake-edu/gopher-shop/book/examples/10-packages/internal/catalog"
    "github.com/dake-edu/gopher-shop/book/examples/10-packages/internal/titlefile"
)
func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
func run() error {
    title, err := titlefile.Load("title.txt")
    if err != nil { return err }
    book := catalog.Book{ID: "go-shop", Title: title, PriceMinor: 249900, Currency: "KZT"}
    if !book.Publish() { return fmt.Errorf("book did not pass validation") }
    fmt.Println(book.Title)
    fmt.Println("Published:", book.Published)
    return nil
}

In catalog.Book the dot selects an exported package name; in book.Title it selects a value's field. The left side distinguishes them. Imports list paths, while catalog comes from the package declaration. An unused import is a compile error. Separate standard-library and project imports with a blank line. gofmt handles formatting, not architectural decisions. A comment for an exported function should begin with its name and explain its contract, including valid inputs and failure.

Verify without guessing

The executable package moved from the root to cmd/shop. Use go run ./cmd/shop, not go run .. Keep the terminal beside go.mod and title.txt: the argument selects a package but does not change the program's working directory.

From 10-packages run:

gofmt -w .
go run ./cmd/shop
go test ./...
go vet ./...
go doc ./internal/catalog Book

The program should print the book title and Published: true. gofmt -w . formats Go files in the current directory and descendants. go vet looks for suspicious constructs, such as a Printf format/type mismatch; successful vet usually prints nothing and does not replace tests. go doc shows the Book declaration and comment locally.

./... covers packages in the current module. [no test files] for cmd/shop can be normal because business tests moved with the rules; absence of tests from every package should prompt a check for missing test files.

In a copy, rename Load to load but leave titlefile.Load in main: compilation fails because the required exported name is unavailable. Restore it. Then run go run . from the chapter root: there is no main package there. The correct command is go run ./cmd/shop. Do not change directory into cmd/shop for this exercise: the relative title.txt path is resolved from the terminal's working directory.

History of changes

Git is optional for running the examples. If installed and you maintain your own learning repository, inspect git status and git diff after passing tests. Add deliberately chosen files, then commit with a meaningful reason. A commit is local; git push sends it to a remote server. Do not add passwords, keys, customer databases, or paid materials without authorization. The full manuscript is stored separately from the book's public teaching repository. An example import path does not publish your own files automatically.

Find the owner of a rule

An empty title must be rejected both after reading a file and when a future form creates a book. Where should the rule live? File and HTTP are two ways to obtain data; the rule must be independent of the input. Keep it in catalog.NormalizeTitle and have both paths use it. In a copy, tighten the rule and verify that file-reading tests notice. Restore the original rule and rerun go test ./....

For “no required module provides package,” compare the module path with import prefixes. For “found packages,” compare package lines within one directory. For “cannot find main module,” move to the directory containing go.mod; do not initialize a module in an accidental terminal location.

Ready for the next chapter: locate a package from its import, explain export and internal, run the tests, and draw dependencies without a cycle.

Why cmd, internal, and web?

cmd/shop is the executable: flags, dependency wiring, startup, and shutdown. internal/catalog holds product rules; internal/titlefile reads titles. The HTTP chapter adds internal/web handlers, and chapter 12 adds top-level web for HTML and CSS. The similar names do not imply the same responsibility.

The internal import boundary is imposed by Go. cmd and web are project conventions. pkg is not a required language standard; do not create an empty directory merely to match a diagram. If another application needs a standalone library, define its API and module boundaries separately. This follows the server-project guidance at https://go.dev/doc/modules/layout. Small early examples lived in the root because splitting them into layers was not yet needed; now locating a rule and following a request matter more than minimizing directory count.

Part I · Junior · Build the storefront

CHAPTER 11 — The Catalog Responds to a Browser

HTTP is a protocol for exchanging requests and responses between clients and servers. The browser is our client and the Go program our server. This chapter produces a local HTTP server with a catalog and a separate URL for a book. The data is not yet modified. Automated request tests do not require an occupied port or a browser.

You need chapter 10's packages, structs, slices, pointers, and functions. Recall why catalog should not import web: the answer matters when separating shop rules from presentation.

A browser requests GET /books/go-shop; ServeMux selects a handler using the method and path; the handler responds with status 200 and the title.
Figure 11.1. A request travels from browser through router to handler.

Running the checkpoint

Open examples/11-http. For a manual transition, copy chapter 10 and change the module path and its prefix in all internal imports to 11-http. Keep catalog and titlefile with their tests. Add internal/catalog/list.go and internal/web; replace cmd/shop/main.go. No web framework installation is needed.

-check is a flag defined by our program: it checks the catalog and exits instead of waiting for a browser. It follows the package path ./cmd/shop; it is not a standard go run feature.

go run ./cmd/shop -check
go test ./...
go run ./cmd/shop

The first command prints Books in catalog: 2 and exits. The last prints an address and keeps running, waiting for requests. Open http://127.0.0.1:8080/ in a browser. Stop the server with Ctrl+C in its terminal. For other commands, use a second terminal in the same directory or stop the server first.

A URL identifies a resource. In http://127.0.0.1:8080/, http is the protocol, the final / is the root path, 127.0.0.1 refers to this computer, and 8080 is the port. Binding this address does not publish the shop on the internet. Do not substitute 0.0.0.0 merely to eliminate an error: that changes which machines may reach the service.

Requests and responses

A browser sends a method and path. GET requests a representation of a resource. A response has a status, headers, and body. 200 indicates success, 404 not found, and 405 an unsupported method for the route.

GET /                  two books, 200
GET /books/go-shop     first book title, 200
GET /books/missing     404
GET /unexpected        404
POST /books/go-shop    405

/books/go-shop need not correspond to a file on disk: it is a path the program matches to a handler. Imagine an information desk directing a question to the appropriate employee. The analogy has a limit: requests are independent and a server may handle several concurrently; do not assume one shared sequential conversation.

Create initial books in internal/catalog/list.go:

package catalog
// Books creates the ordered initial catalog from the validated file title.
func Books(title string) ([]Book, bool) {
    books := []Book{
        {ID: "go-shop", Title: title, PriceMinor: 249900, Currency: "KZT"},
        {ID: "go-tests", Title: "Go Testing", PriceMinor: 150000, Currency: "KZT"},
    }
    for i := range books {
        if !books[i].Publish() { return nil, false }
    }
    return books, true
}

Publish still validates title, price, and currency. books[i] changes the original slice element; a range value would be a copy. On an invalid card, return false instead of starting a server with a partially invalid catalog.

A handler without a listening server

Before the full routes, trace one call. home accepts an interface used to write a response and a pointer to the request. Header().Set sets a response header; fmt.Fprintln writes to the supplied object rather than the terminal. The handler does not return a string: the response object accumulates its output.

Save labs/01-handler/main.go:

package main
import (
    "fmt"
    "net/http"
    "net/http/httptest"
)
func home(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    fmt.Fprintln(w, "Go shop")
}
func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /{$}", home)
    request := httptest.NewRequest("GET", "/", nil)
    response := httptest.NewRecorder()
    mux.ServeHTTP(response, request)
    fmt.Println(response.Code)
    fmt.Print(response.Body.String())
    missing := httptest.NewRecorder()
    mux.ServeHTTP(missing, httptest.NewRequest("GET", "/missing", nil))
    fmt.Println(missing.Code)
}

From the chapter root, go run ./labs/01-handler prints:

200
Go shop
404

No port opens. httptest is a standard-library package for in-memory requests and responses. NewRequest creates a request and NewRecorder a response recorder; Code and Body expose the result. nil gives the request an empty body.

In HandleFunc("GET /{$}", home), the function is passed without being called, as in chapter 9. Later mux.ServeHTTP(response, request) selects a route and calls home. The first body write selects 200 unless a status was explicitly sent. /missing has no matching route, so the response is 404.

Trace main → ServeHTTP → home → Fprintln → return to main before running. Change the request path to /missing without changing the route: home is not called. Restore it and add a separate /healthz handler as preparation for the exercise.

ResponseWriter and Handler are standard-library interfaces. The former supplies response-writing methods; the latter supplies ServeHTTP. As with error, concrete values satisfy the contract through their methods. Chapter 18 explores custom interfaces and method sets; for now distinguish a function value from its call, and an interface from a pointer to a struct.

Handler and router

Save internal/web/web.go, using the actual module prefix from go.mod:

package web
import (
    "fmt"
    "net/http"
    "github.com/dake-edu/gopher-shop/book/examples/11-http/internal/catalog"
)
// New copies the catalog; handlers only read this snapshot.
func New(books []catalog.Book) http.Handler {
    snapshot := make([]catalog.Book, len(books))
    copy(snapshot, books)
    mux := http.NewServeMux()
    mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "text/plain; charset=utf-8")
        for _, book := range snapshot { fmt.Fprintln(w, book.ID, book.Title) }
    })
    mux.HandleFunc("GET /books/{id}", func(w http.ResponseWriter, r *http.Request) {
        for _, book := range snapshot {
            if book.ID == r.PathValue("id") {
                w.Header().Set("Content-Type", "text/plain; charset=utf-8")
                fmt.Fprintln(w, book.Title)
                return
            }
        }
        http.NotFound(w, r)
    })
    return mux
}

NewServeMux creates a router and HandleFunc associates a route pattern with a function. GET /{$} includes the method and matches exactly the root; a plain / would also match other paths. In /books/{id}, braces denote a variable path segment; r.PathValue("id") returns it. They are route syntax inside a string, not Go block braces.

A handler writes via w http.ResponseWriter and reads the request via r *http.Request. Set Content-Type before the first body write. fmt.Fprintln(w, ...) sends text to the response rather than the terminal. The first body write without explicit WriteHeader selects 200. http.NotFound writes 404 and a body; do not append a successful response after it.

The returned http.Handler promises ServeHTTP. Our mux satisfies that contract, so the same handler can serve a real server or a test.

The route functions close over snapshot. We allocate a new slice and copy the cards, so later changes to the caller's slice do not change the handler catalog. Our current Book contains strings, numbers, and a bool; value copying suffices. Adding a map or slice field later would not automatically produce a deep copy.

Handlers only read the snapshot. This matters because the server can call them concurrently. Do not add shared mutable state without synchronization. We will study concurrent execution later; for now the model excludes shared writes.

Process lifecycle

Save cmd/shop/main.go:

package main
import (
    "errors"
    "flag"
    "fmt"
    "net/http"
    "os"
    "time"
    "github.com/dake-edu/gopher-shop/book/examples/11-http/internal/catalog"
    "github.com/dake-edu/gopher-shop/book/examples/11-http/internal/titlefile"
    "github.com/dake-edu/gopher-shop/book/examples/11-http/internal/web"
)
func main() {
    if err := run(); err != nil { fmt.Fprintln(os.Stderr, err); os.Exit(1) }
}
func run() error {
    check := flag.Bool("check", false, "check catalog without starting the server")
    flag.Parse()
    title, err := titlefile.Load("title.txt")
    if err != nil { return err }
    books, ok := catalog.Books(title)
    if !ok { return errors.New("invalid catalog") }
    if *check { fmt.Println("Books in catalog:", len(books)); return nil }
    server := &http.Server{
        Addr: "127.0.0.1:8080", Handler: web.New(books),
        ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second,
        WriteTimeout: 15 * time.Second, IdleTimeout: time.Minute,
    }
    fmt.Println("Open http://127.0.0.1:8080; stop with Ctrl+C")
    return server.ListenAndServe()
}

flag.Bool declares a Boolean flag and returns a pointer to its value: the arguments are name, default, and help text. flag.Parse reads command-line arguments; afterward *check gives the chosen value. In go run ./cmd/shop -check, arguments after the package path go to the shop. go run ./cmd/shop -h prints this program's flag help, which may change between chapters.

time.Second and time.Minute are durations. The timeout fields bound reading headers, reading a request, writing a response, and waiting for another request on a connection. These values suit small educational responses; they are not yet a policy for multi-gigabyte downloads.

ListenAndServe occupies the call until an error or shutdown. Here Ctrl+C interrupts the process. Graceful completion of active requests appears in the chapter about context and shutdown; do not call the current shutdown graceful.

Test HTTP without a network

Save internal/web/web_test.go:

package web
import (
    "net/http/httptest"
    "strings"
    "testing"
    "github.com/dake-edu/gopher-shop/book/examples/11-http/internal/catalog"
)
func TestRoutes(t *testing.T) {
    books, ok := catalog.Books("Go")
    if !ok { t.Fatal("invalid fixture") }
    handler := New(books)
    books[0].Title = "Changed outside"
    for _, tc := range []struct {
        method, path string
        code int
    }{
        {"GET", "/", 200}, {"GET", "/books/go-shop", 200},
        {"GET", "/books/missing", 404}, {"GET", "/missing", 404},
        {"POST", "/books/go-shop", 405},
    } {
        w := httptest.NewRecorder()
        handler.ServeHTTP(w, httptest.NewRequest(tc.method, tc.path, nil))
        if w.Code != tc.code { t.Fatalf("%s %s: %d", tc.method, tc.path, w.Code) }
        if strings.Contains(w.Body.String(), "Changed outside") { t.Fatal("catalog aliases caller") }
    }
}

NewRequest creates an in-memory request and NewRecorder records the response. ServeHTTP invokes the same handler code used by the browser. The []struct{...} literal is a table of cases without a separately named type; method, path, and code explain each row.

This test checks routing, not the listening port, TLS, or network timeouts. Open the page in a browser once separately, then rerun go test ./... after changes.

Exercise and recovery

Add GET /healthz returning ok and a newline with status 200. First add a case to the table and confirm that the test fails with 404. Add mux.HandleFunc before return mux; a handler with fmt.Fprintln(w, "ok") makes it pass. This only checks process availability, not future database readiness. Separately check that POST /healthz gets 405.

“address already in use” means the port is occupied, often by your previous run: stop it with Ctrl+C. If you change Addr, change the browser address too. If the browser shows old text, restart the server after editing; go run does not watch files automatically.

Ready to proceed: distinguish a route from a filesystem path, explain 404 and 405, start and stop the server, and test a request without opening a network port.

Part I · Junior · Build the storefront

CHAPTER 12 — An HTML Template Turns the Catalog into a Page

The catalog will gain headings, links, prices, and simple styling. We keep the server and book rules, changing the presentation of its response. No external bundler, JavaScript, or CSS framework is required.

Before starting, explain why response headers are set before the body and why an unknown book yields 404. If unsure, repeat chapter 11's route tests.

Book data becomes pageData, html/template escapes the values, and the completed HTML is buffered before being sent as an HTTP response.
Figure 12.1. Data and presentation.

Files and a quick result

Open examples/12-templates. For a manual transition, copy chapter 11 and consistently change the module path and internal import prefixes from 11-http to 12-templates. Replace internal/web/web.go; add templates.go, template_test.go, and footer_test.go while retaining web_test.go. Copy the checkpoint's web tree: assets.go, templates/layouts, templates/pages, templates/partials, and static/css/style.css. The other packages retain their behavior. The companion checkpoint contains the complete files referred to below; preserve a clean copy before experimenting.

go test ./...
go run ./cmd/shop

Open http://127.0.0.1:8080/: two cards should appear. The menu currently contains only eGopher. The cart arrives in chapter 13, registration in 19, and login in 20. Add links together with working routes; their current absence is intentional. A title link opens an individual book page; a missing book still yields 404. Stop the server with Ctrl+C.

Enough HTML to read the template

HTML marks document meaning. <h1> is the main heading, <article> a self-contained card, <a href="..."> a link, and <p> a paragraph. A closing tag begins with </. Attributes in an opening tag set properties. HTML is not Go code.

lang="en" identifies the page language for assistive technology; charset="utf-8" specifies encoding. viewport lets the page account for screen width. <main> identifies the main content, and a #content skip link provides a keyboard shortcut to it. Start with meaning and reading order, then style.

First, one substitution

Open labs/01-template/main.go and run its command from the chapter root:

package main
import (
    "fmt"
    "html/template"
    "os"
)
type Page struct{ Title string }
func run() error {
    page, err := template.New("card").Parse("<h1>{{.Title}}</h1>\n")
    if err != nil { return err }
    return page.Execute(os.Stdout, Page{Title: "<Go>"})
}
func main() {
    if err := run(); err != nil { fmt.Fprintln(os.Stderr, err); os.Exit(1) }
}

go run ./labs/01-template prints:

<h1>&lt;Go&gt;</h1>

template.New("card") creates a named template set. Parse parses template text and may fail; Execute uses concrete data and writes to os.Stdout. Parsing and execution are distinct stages. {{.Title}} reads the Title field of the Page passed to Execute.

The input <Go> becomes &lt; and &gt;, HTML entities for angle brackets. A browser displays the title as text instead of a new HTML tag. A terminal prints markup; it is not a browser. Change the title to Go & SQL and expect Go &amp; SQL between the tags; restore the original afterward. An unknown field such as {{.Missing}} can fail at execution when data is available; an unfinished action such as {{ fails during parsing. A handler must not send half of a successful response before discovering an execution error.

Then a layout and a reusable part

define declares a named template; template executes it. The quoted name is a key in the set, not necessarily the filename. The final dot passes the current data to the nested template.

package main
import (
    "fmt"
    "html/template"
    "os"
)
type Page struct{ Title string }
func run() error {
    source := `{{define "base"}}<main>{{template "content" .}}</main>{{template "footer" .}}
{{end}}{{define "content"}}<h1>{{.Title}}</h1>{{end}}{{define "footer"}}<footer>eGopher</footer>{{end}}`
    page, err := template.New("pages").Parse(source)
    if err != nil { return err }
    return page.ExecuteTemplate(os.Stdout, "base", Page{Title: "Go"})
}
func main() {
    if err := run(); err != nil { fmt.Fprintln(os.Stderr, err); os.Exit(1) }
}

go run ./labs/02-layout prints:

<main><h1>Go</h1></main><footer>eGopher</footer>

ExecuteTemplate selects base; base calls content and footer. Only content reads Title. Change Page.Title: the heading changes while layout and footer remain. Remove the dot from {{template "content" .}} and observe the missing data; restore it. The exercise establishes why the argument matters.

In the shop, these definitions live in separate layout, page, and partial files. embed ships them with the program; CSS determines their presentation. The core idea stays the same: data → template execution → HTML.

The catalog page

The checkpoint's web/templates/pages/home.html contains:

{{define "title"}}{{.Title}}{{end}}
{{define "content"}}
<h1>{{.Title}}</h1>
{{range .Books}}
    <article>
        <h2><a href="/books/{{.ID}}">{{.Title}}</a></h2>
        <p>{{money .PriceMinor}} {{.Currency}}</p>
    </article>
{{else}}
    <p>The catalog is currently empty.</p>
{{end}}
{{end}}

Double braces mark template actions. {{.Title}} reads the current data's Title. {{range .Books}} iterates books; inside the loop dot is the current book. {{else}} supplies content for an empty slice; {{end}} ends the block. These are html/template rules, not Go syntax.

{{money .PriceMinor}} calls a registered formatting function. Our price is an integer in minor units; division by 100 gives the whole part and % 100 the remainder. %02d pads the remainder to at least two positions: 105 becomes 1.05. This helper is for nonnegative prices in our two-decimal currency model, not a universal money library.

Public assets and their boundaries

The checkpoint organizes public assets under web/static/: brand for the logo, css/style.css for styles, js for future browser scripts, and images for public images. Empty .gitkeep files retain otherwise empty directories in Git; they are ordinary files, not Git commands. JavaScript is not required here.

brand holds persistent identity assets; images is for public illustrations and product covers. Paid books, databases, keys, and customer uploads do not belong in this public tree. A file on disk does not automatically gain a URL: the server explicitly serves the CSS and selected brand images. The disk path web/static/css/style.css is distinct from the /assets/css/style.css URL. Add future resource types intentionally, without exposing directory listings.

The logo and icons have different jobs. brand/gopher-cart.png is a transparent 256×256 PNG, displayed at 80×80 in the header. A smaller favicon uses a simplified gopher head; favicon.ico contains 16×16 and 32×32 sizes. apple-touch-icon.png is a 180×180 icon for a device home screen. It does not make this a complete installable app: there is no offline behavior or app manifest here. Source artwork and rights information belong with the editorial assets.

base.html links to the favicon, touch icon, and CSS. header.html loads the logo with width and height to reserve space. The logo link gets an accessible aria-label; the image uses empty alt="" so a screen reader does not repeat the link name. A nav with its own accessible label groups menu links. brand_name supplies eGopher for header, footer, and tab title.

Explicitly register allowed image routes in internal/web/brand.go:

package web
import (
    "net/http"
    assets "github.com/dake-edu/gopher-shop/book/examples/12-templates/web"
)
func registerBrand(mux *http.ServeMux) {
    serveImage(mux, "/assets/brand/gopher-cart.png", "image/png", assets.Logo)
    serveImage(mux, "/favicon.ico", "image/vnd.microsoft.icon", assets.Favicon)
    serveImage(mux, "/assets/brand/apple-touch-icon.png", "image/png", assets.TouchIcon)
}
func serveImage(mux *http.ServeMux, path, contentType string, data []byte) {
    mux.HandleFunc("GET "+path, func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", contentType)
        _, _ = w.Write(data)
    })
}

Call registerBrand(mux) after creating the router. Only the three listed routes are registered; an arbitrary directory is not served. w.Write sends binary bytes, not text. Here the single write result is explicitly ignored: another write cannot restore a disconnected client. The images are embedded in the executable; replacing them requires a rebuild. Open /favicon.ico directly if a browser tab seems to show a cached icon. TestBrandAssetsAndClosedDirectory checks the embedded files and rejects unknown files and directory requests.

Rendering a response

The complete internal/web/web.go in the checkpoint defines pageData, money, and New. New copies the catalog, prepares the home template, registers the brand and CSS routes, and registers the catalog and book routes. The essential rendering sequence is:

var out bytes.Buffer
if err := page.Execute(&out, data); err != nil {
    http.Error(w, "Could not display the page", http.StatusInternalServerError)
    return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = out.WriteTo(w)

Render into memory first. If Execute fails, the handler can still send a 500 status. Writing directly to the network might already send part of a successful page, too late to change the status. After successful execution, set Content-Type and write the buffer. A later network-write failure cannot be repaired by sending a new status; later chapters add observability.

pageData is data for one presentation. Do not hand the template the entire server or a future user record containing a password. append([]catalog.Book(nil), books...) copies slice elements: the initial expression is a typed nil slice and ... passes the elements to append, not missing code. It is a shorter form of make and copy; nested references in future elements would still need attention.

Embedding and template sets

The top-level web package is named assets to distinguish it from HTTP handlers. Its assets.go uses //go:embed templates static to include those trees in read-only embed.FS. Paths are relative to the file with the directive and cannot escape upward via .. Separate variables embed CSS as a string and the logo and icons as []byte. Read the complete assets.go in the checkpoint; changes to embedded HTML or CSS require rerunning go run ./cmd/shop.

A layout supplies the document skeleton. {{define "base"}} names a template; {{template "content" .}} executes another and passes it the current data. Partials are reusable pieces such as header and footer. They are a project convention built with Go's standard library, not a separate template engine.

The base layout specifies lang="en", UTF-8, the viewport, a skip link to #content, the header, a main region, and the footer. The header's logo link has an accessible name; its decorative image has an empty alt; nav has an accessible label. The page file defines title and content. See the complete files in web/templates/layouts, pages, and partials.

The footer uses &copy; to display © and calls {{year}} and {{brand_name}} without a leading dot: those are functions, unlike the data field {{.Title}}. It can therefore be shared by pages with different data structures. The English checkpoint also includes a visible attribution for the Go gopher and its adapted artwork, with links to its source and license.

Each page gets its own template set: common layout, common partials, and exactly one page file. Parsing every page into one set would cause repeated content definitions to replace one another. ParseFS reads embedded assets.Files and a *.html pattern selects partials. Our startup code chooses the page name, not an untrusted URL parameter. Prepared sets are not changed while serving requests.

The complete pageTemplate implementation is in internal/web/templates.go. It registers nav_active, money, year, and brand_name through template.FuncMap before ParseFS; otherwise parsing fails with an undefined function. template.Must stops startup if a supplied embedded template is invalid. That is a deliberate boundary for a defect in the shipped program; later user input errors should be returned as ordinary responses.

The year function calls time.Now().Year() during each page execution rather than storing a startup-year constant. A running server can display the next year after the local calendar changes; an already open tab updates when reloaded. The process's local timezone determines the boundary. For a particular region, configure a timezone deliberately. footer_test.go uses a test clock for 2026 and 2027 without changing the system clock or waiting for New Year.

Text must not become a program

html/template contextually escapes ordinary strings. If a title contains <script>, the browser should display text, not run a script. Do not convert untrusted input to template.HTML: that type marks HTML as trusted and bypasses part of the automatic protection.

The checkpoint's TestEscapeAndEmptyCatalog passes nil for the empty catalog and a title containing <script>alert(1)</script> for escaping, then checks the response with httptest. Read the full test in internal/web/template_test.go and run go test ./.... These checks cover selected scenarios, not all web-security risks.

CSS, accessibility, and responsive layout

Read the full web/static/css/style.css in the companion checkpoint. CSS selectors identify elements; declarations such as text-align: center consist of a property, colon, value, and semicolon. rem scales relative to the root font size. CSS describes presentation, not Go execution.

The layout starts with one column. box-sizing: border-box includes padding and border in a specified width. max-width constrains content; inputs fit their parent; min-width: 0 allows flex/grid children to shrink. overflow-wrap: anywhere lets a long ID, email address, or hash wrap. Do not hide a layout problem with overflow-x: hidden, which can simply make content inaccessible.

Forms use grid and gap; navigation uses flex and allows links to wrap. clamp bounds heading size while allowing a viewport-dependent value between the limits. Input and button minimum height of 2.75rem is this project's touch-target choice, not proof of full accessibility. :not excludes checkboxes and hidden inputs from text-field rules; :has(input[type="checkbox"]) adjusts the enclosing label when supported. @media (min-width: 40rem) changes spacing when more room is available. No special device-name detection or zoom restriction is required.

The footer is centered. html has height: 100%; body uses min-height, flex, and column direction. A 100dvh declaration provides dynamic viewport height where supported, with the percentage rule as fallback. min-height permits longer content to grow. footer's margin-top: auto uses remaining space to move it toward the bottom on a short page; on a long page it follows content. flex-shrink: 0 prevents footer shrinking. A fixed-position footer could cover text and buttons.

On wider screens the header keeps the logo to the left and navigation to the right, allowing the links themselves to wrap. On narrow screens a media query stacks the logo and menu. Keep links usable when text is enlarged or translations are longer rather than forcing a single line.

Check a short book page, a long catalog, and a phone-sized viewport in both orientations. The footer must follow content, the logo remain visible, and navigation remain usable without horizontal page scrolling. Use Tab to move through links and Enter to activate one; zoom to 200% and narrow the window. These checks help find defects but are not a complete accessibility audit. A desktop emulator does not fully reproduce an actual mobile browser or on-screen keyboard; test real devices before a commercial release.

The root layout sets width=device-width and initial-scale=1, without maximum-scale. Later, after forms and login exist, test them at 320×568, 390×844, 844×390, 768×1024, 1024×768, and 1366×768. Vertical scrolling of a long form is normal. The final example footer labels the site an educational online store; later payment examples remain a sandbox and do not charge money.

The active menu section

nav_active compares a section key with active, chosen while preparing a template. The catalog and book page use catalog; later cart and order pages use cart, while login, library, and administration use account. The header condition adds aria-current="true" only to the active link. It indicates the current section, not necessarily an exact URL match: a book page remains in the catalog section. Screen-reader users receive the same state that sighted readers see through styling.

The CSS selector header nav a[aria-current="true"] uses a teal background and white text. Padding on all items prevents width jumps when the active item changes. text-decoration: none applies only to header navigation; links in content remain underlined. :focus-visible retains a visible keyboard-focus outline.

active belongs to the closure of a particular prepared template. Do not change a shared “current page” variable on every request: concurrent visitors could see each other's highlighting. Later, catalog and cart can use the same page file with separately prepared template sets. This separates request data from immutable display configuration.

border-radius: 0.5rem gives controls and active navigation consistent rounding; at a 16-pixel root size it is 8 pixels. The footer shares the teal and white theme, padding, and rounded corners. Placement still depends on flex and margin-top: auto. CSS custom properties --color-primary and --color-on-primary are declared in :root and referenced with var(...). Changing them changes the shared theme; rebuild the application after editing embedded CSS.

Try it: an empty catalog

Predict the page for New(nil), then find the check in template_test.go. Change the expected message to “New books are coming soon” first and see the test fail; then change only the range block's else text and rerun. Restore the original before the next checkpoint. The template's else is enough; no separate length check in Go is required.

Troubleshooting

For “no matching files found,” check the resource tree beside web/assets.go. If ParseFS cannot find a page, check its filename under web/templates/pages. A template parse failure can indicate unmatched range/end actions or unregistered functions. If styling disappears, open /assets/css/style.css: expect CSS, not a 404 HTML page.

You are ready to proceed when you can distinguish Go, HTML, CSS, and template actions; explain automatic escaping and buffering; test an empty catalog; and navigate the page by keyboard. See https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/CSS_layout/Responsive_Design for responsive-design background.

Back to contents · Shanraq