Go (Golang)
This chapter builds Go's value, interface, error, goroutine, channel, cancellation, HTTP, database, gRPC, testing, and deployment models as one production backend toolkit.
- Explain Go basics by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Go for backend by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
How to use this chapter
For Go (Golang), read the explanations first and predict every example before running it. Keep a learning repository containing code, tests, command output, and the short written submission. The roadmap checklist at the end audits coverage; the chapter itself follows the language learning arc appropriate to this subject.
The problem this chapter solves
This chapter builds Go's value, interface, error, goroutine, channel, cancellation, HTTP, database, gRPC, testing, and deployment models as one production backend toolkit.
Its small language and strong tooling make service code predictable while goroutines and channels provide inexpensive concurrency.
Learning outcomes
- Explain Go basics by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Explain Go for backend by naming its input, guarantee, internal lifecycle, important failure, and proof.
- Trace the chapter's complete execution path and identify where memory, I/O, concurrency, persistence, or rendering cost accumulates.
- Build the worked example, make one failure visible, and defend the design in a review.
Chapter progression
The order below is intentional: later sections depend on guarantees established earlier.
Runtime or system overview
The runtime schedules many goroutines over a smaller set of operating-system threads. Stacks begin small and grow. Interfaces carry dynamic type and value information. Escape analysis decides whether values can remain on a stack or must move to the heap; the concurrent garbage collector manages heap objects. In Go (Golang), use that execution model to decide where the chapter's validation, state ownership, cleanup, and evidence belong.
Execution trace
- The Go compiler type-checks packages, resolves interfaces and escape behavior, and links one executable before the process starts.
- The handler receives a request context, validates input, and calls explicit service and repository functions while propagating cancellation and deadlines.
- The runtime schedules goroutines over operating-system threads; channels, mutexes, and database pools impose the synchronization and capacity boundaries.
- Errors wrap causal context and return normally; deferred cleanup runs in last-in-first-out order on return or panic; the boundary maps failure to a stable response.
- Table-driven tests, the race detector, benchmarks, cancellation tests, and service telemetry verify correctness and resource behavior.
Memory and performance lens
Slices are descriptors over arrays, maps are reference-like runtime structures, and interfaces can retain concrete values. Goroutine leaks retain stacks and referenced objects. Reuse and pooling are advanced optimizations that should follow profiling. For Go (Golang), connect those costs to the concrete operations in the topic sections rather than assuming the friendly surface syntax is cheap.
When tuning Go (Golang), measure allocation count, retained-object size, iterator materialization, CPU profile, file/network call count, and execution time on representative input rather than optimizing from source-code appearance.
1. Go basics
The Go basics unit begins with types/structs/interfaces/embedding: Go's built-in and defined types have static method sets; structs compose fields, interfaces describe required methods implicitly, and embedding promotes selected fields or methods without creating subclass inheritance. Use small consumer-owned interfaces and composition; return concrete types unless callers need substitution. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Go basics
| Concept | Meaning | Engineering decision |
|---|---|---|
| types/structs/interfaces/embedding | Go's built-in and defined types have static method sets; structs compose fields, interfaces describe required methods implicitly, and embedding promotes selected fields or methods without creating subclass inheritance. | Use small consumer-owned interfaces and composition; return concrete types unless callers need substitution. |
| goroutines + channels (unbuffered/buffered/select/done pattern) | A goroutine is a runtime-scheduled concurrent function; unbuffered channels synchronize sender and receiver, buffered channels decouple them up to capacity, and select waits on multiple channel operations. | Pass context cancellation, make the producer own channel closure, and bound workers and buffers. |
| defer/panic/recover | defer schedules cleanup for function exit, panic begins stack unwinding, and recover can intercept a panic only from a deferred call in the same goroutine. | Use defer for close/unlock, return ordinary errors for expected failures, and recover only at server/process boundaries that can isolate the request. |
| error handling: errors.Is/As/wrapping | Go errors are explicit values that can wrap a causal chain; modules give packages a versioned dependency identity and checksum record. | Wrap with operation context, match stable sentinel/types through Is/As, and commit go.mod/go.sum. |
| packages + modules: go.mod/go.sum | Go errors are explicit values that can wrap a causal chain; modules give packages a versioned dependency identity and checksum record. | Wrap with operation context, match stable sentinel/types through Is/As, and commit go.mod/go.sum. |
What the runtime actually does: Go basics
types/structs/interfaces/embedding. An interface value stores a dynamic type and value. A pointer and its value can have different method sets. Embedded fields participate in selector promotion, while name conflicts require explicit qualification.
goroutines + channels (unbuffered/buffered/select/done pattern). The Go scheduler multiplexes goroutines over OS threads. Send/receive operations establish happens-before relationships; closing a channel broadcasts that no further values will be sent, while receiving can continue until the buffer drains.
defer/panic/recover. Deferred call arguments are evaluated immediately and calls execute last-in-first-out. Panic runs deferred cleanup while unwinding; recover outside the required boundary returns nil.
error handling: errors.Is/As/wrapping. fmt.Errorf with %w preserves an unwrap chain inspected by errors.Is/As. Minimal version selection chooses module versions and go.sum authenticates downloaded module content.
packages + modules: go.mod/go.sum. fmt.Errorf with %w preserves an unwrap chain inspected by errors.Is/As. Minimal version selection chooses module versions and go.sum authenticates downloaded module content.
Read these as one system: types/structs/interfaces/embedding establishes the starting contract, goroutines + channels (unbuffered/buffered/select/done pattern) changes how that contract is executed or represented, and packages + modules: go.mod/go.sum exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Read the syntax in context: Go basics
1type User struct { ID string; Name string }2type Reader interface { Read(context.Context, string) (User, error) }This Go basics slice makes types/structs/interfaces/embedding observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward packages + modules: go.mod/go.sum, predict its behavior for empty, invalid, repeated, and large input.
Mistakes that change program meaning: Go basics
| Risk | Why it matters |
|---|---|
| types/structs/interfaces/embedding | A typed nil pointer stored in a non-nil interface makes the interface itself non-nil, a frequent source of incorrect nil checks. |
| goroutines + channels (unbuffered/buffered/select/done pattern) | A goroutine blocked on a send, receive, or missing cancellation path leaks its stack and all referenced data. |
| defer/panic/recover | Recovering and continuing with corrupted shared state hides a defect; panic is not routine validation. |
| error handling: errors.Is/As/wrapping | Comparing wrapped errors directly or parsing error strings breaks as soon as context is added. |
| packages + modules: go.mod/go.sum | Comparing wrapped errors directly or parsing error strings breaks as soon as context is added. |
Code it, observe it, explain it: Go basics
- Foundation: implement or demonstrate types/structs/interfaces/embedding with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine types/structs/interfaces/embedding with goroutines + channels (unbuffered/buffered/select/done pattern). Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for packages + modules: go.mod/go.sum. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
2. Go for backend
The Go for backend unit begins with net/http standard library handlers: Go HTTP handlers receive a request carrying cancellation context and write one response; gin layers routing, middleware, binding, and validation conventions over net/http. Set server read/write/idle timeouts, validate once at the boundary, and propagate request context. The rest of this section connects that guarantee to this unit's related roadmap concepts instead of treating each term as an isolated flashcard.
The language model: Go for backend
| Concept | Meaning | Engineering decision |
|---|---|---|
| net/http standard library handlers | Go HTTP handlers receive a request carrying cancellation context and write one response; gin layers routing, middleware, binding, and validation conventions over net/http. | Set server read/write/idle timeouts, validate once at the boundary, and propagate request context. |
| gin framework: routing/middleware/binding/validation | Go HTTP handlers receive a request carrying cancellation context and write one response; gin layers routing, middleware, binding, and validation conventions over net/http. | Set server read/write/idle timeouts, validate once at the boundary, and propagate request context. |
| database/sql + sqlx for PostgreSQL | database/sql is a concurrency-safe connection-pool handle; sqlx adds mapping and named-query convenience without changing transaction semantics. | Bound open/idle/lifetime settings, close rows, inspect rows.Err, and pass a transaction explicitly through repository methods. |
| gRPC: .proto file, service definition, unary + streaming | Protocol Buffers define numbered, versionable messages and gRPC generates typed unary or streaming client/server interfaces over HTTP/2. | Reserve removed field numbers, set deadlines, map domain errors to stable status codes, and add interceptors for auth and telemetry. |
| testing: TestXxx, table-driven tests, t.Parallel(), benchmarks | Go tests are ordinary TestXxx functions; table-driven subtests compactly express cases, parallel tests expose unsafe sharing, and benchmarks measure repeated operations with controlled setup. | Capture each case variable, use -race, report allocations, and benchmark representative data outside setup timing. |
What the runtime actually does: Go for backend
net/http standard library handlers. The server runs handlers concurrently, so shared state requires synchronization. Middleware wraps handlers in registration order and request bodies must be bounded and closed where applicable.
gin framework: routing/middleware/binding/validation. The server runs handlers concurrently, so shared state requires synchronization. Middleware wraps handlers in registration order and request bodies must be bounded and closed where applicable.
database/sql + sqlx for PostgreSQL. A query borrows a connection, rows retain it until closed, and a transaction pins one connection until commit/rollback. Context cancellation can abort waits or driver work when supported.
gRPC: .proto file, service definition, unary + streaming. protoc plugins generate Go types and service stubs. Deadlines and cancellation propagate in context; streams require explicit send/receive loops and backpressure/error handling.
testing: TestXxx, table-driven tests, t.Parallel(), benchmarks. go test builds a temporary test binary, the race detector instruments accesses, and the benchmark runner adjusts iteration count. Parallel subtests run after the parent yields.
Read these as one system: net/http standard library handlers establishes the starting contract, gin framework: routing/middleware/binding/validation changes how that contract is executed or represented, and testing: TestXxx, table-driven tests, t.Parallel(), benchmarks exposes a later boundary or failure condition. A local optimization is useful only when the combined behavior stays correct and observable.
Read the syntax in context: Go for backend
1mux := http.NewServeMux()2mux.HandleFunc("GET /users/{id}", getUser)This Go for backend slice makes net/http standard library handlers observable. Read it from the boundary inward: identify the input, the validation point, the state or operation, and the value that proves the result. Before extending it toward testing: TestXxx, table-driven tests, t.Parallel(), benchmarks, predict its behavior for empty, invalid, repeated, and large input.
Mistakes that change program meaning: Go for backend
| Risk | Why it matters |
|---|---|
| net/http standard library handlers | Using the default server with no timeouts or sharing mutable maps across handlers creates resource and race failures. |
| gin framework: routing/middleware/binding/validation | Using the default server with no timeouts or sharing mutable maps across handlers creates resource and race failures. |
| database/sql + sqlx for PostgreSQL | Treating sql.DB as one connection or forgetting rows.Close can exhaust the pool. |
| gRPC: .proto file, service definition, unary + streaming | Reusing a field number with new meaning or retrying a non-idempotent RPC breaks compatibility or duplicates effects. |
| testing: TestXxx, table-driven tests, t.Parallel(), benchmarks | Calling t.Parallel with shared mutable fixtures or benchmarking compiler-eliminated work produces misleading results. |
Code it, observe it, explain it: Go for backend
- Foundation: implement or demonstrate net/http standard library handlers with one valid input and one invalid input. Record the exact output or failure.
- Integration: combine net/http standard library handlers with gin framework: routing/middleware/binding/validation. Explain which component owns validation and cleanup.
- Production: design a test or experiment that exposes the failure described for testing: TestXxx, table-driven tests, t.Parallel(), benchmarks. State the metric, assertion, or query plan that proves the correction.
What a strong checkpoint answer contains
- A precise boundary and typed or validated input.
- One named guarantee, not only a library call.
- A negative case that fails for the intended reason.
- Cleanup, transaction, retry, or cancellation behavior where applicable.
- Evidence: assertion, command output, plan, trace, metric, or accessible UI state.
Complete worked example
This example integrates the chapter rather than demonstrating an isolated method.
1package main2
3import (4 "context"5 "encoding/json"6 "errors"7 "net/http"8 "time"9)10
11type User struct { ID string `json:"id"`; Name string `json:"name"` }12type Repository interface { Get(context.Context, string) (User, error) }13
14func userHandler(repo Repository) http.HandlerFunc {15 return func(w http.ResponseWriter, r *http.Request) {16 ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)17 defer cancel()18 user, err := repo.Get(ctx, r.PathValue("id"))19 if errors.Is(err, ErrNotFound) { http.Error(w, "not found", http.StatusNotFound); return }20 if err != nil { http.Error(w, "unavailable", http.StatusServiceUnavailable); return }21 w.Header().Set("Content-Type", "application/json")22 json.NewEncoder(w).Encode(user)23 }24}Expected result
1The handler propagates cancellation, maps domain errors to HTTP status, and writes a typed JSON response.Line-by-line reading
| Line | Code | Explanation |
|---|---|---|
| 1 | package main | Implements the next go statement in the example's data flow. |
| 3 | import ( | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 4 | "context" | Implements the next go statement in the example's data flow. |
| 5 | "encoding/json" | Implements the next go statement in the example's data flow. |
| 6 | "errors" | Implements the next go statement in the example's data flow. |
| 7 | "net/http" | Implements the next go statement in the example's data flow. |
| 8 | "time" | Implements the next go statement in the example's data flow. |
| 9 | ) | Implements the next go statement in the example's data flow. |
| 11 | type User struct { ID string \json:"id"\; Name string \json:"name"\ } | Implements the next go statement in the example's data flow. |
| 12 | type Repository interface { Get(context.Context, string) (User, error) } | Implements the next go statement in the example's data flow. |
| 14 | func userHandler(repo Repository) http.HandlerFunc { | Implements the next go statement in the example's data flow. |
| 15 | return func(w http.ResponseWriter, r *http.Request) { | Returns the observable result to the caller and ends this invocation. |
| 16 | ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 17 | defer cancel() | Defines failure translation or cleanup that must run around the protected operation. |
| 18 | user, err := repo.Get(ctx, r.PathValue("id")) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 19 | if errors.Is(err, ErrNotFound) { http.Error(w, "not found", http.StatusNotFound); return } | Evaluates the condition and enters this branch only when it is truthy. |
| 20 | if err != nil { http.Error(w, "unavailable", http.StatusServiceUnavailable); return } | Evaluates the condition and enters this branch only when it is truthy. |
| 21 | w.Header().Set("Content-Type", "application/json") | Implements the next go statement in the example's data flow. |
| 22 | json.NewEncoder(w).Encode(user) | Implements the next go statement in the example's data flow. |
| 23 | } | Implements the next go statement in the example's data flow. |
| 24 | } | Implements the next go statement in the example's data flow. |
Step-by-step execution
- The Go compiler type-checks packages, resolves interfaces and escape behavior, and links one executable before the process starts.
- The handler receives a request context, validates input, and calls explicit service and repository functions while propagating cancellation and deadlines.
- The runtime schedules goroutines over operating-system threads; channels, mutexes, and database pools impose the synchronization and capacity boundaries.
- Errors wrap causal context and return normally; deferred cleanup runs in last-in-first-out order on return or panic; the boundary maps failure to a stable response.
- Table-driven tests, the race detector, benchmarks, cancellation tests, and service telemetry verify correctness and resource behavior.
Common mistakes and professional corrections
| Area | Common failure | Better engineering choice |
|---|---|---|
| Go basics | A typed nil pointer stored in a non-nil interface makes the interface itself non-nil, a frequent source of incorrect nil checks. | Use small consumer-owned interfaces and composition; return concrete types unless callers need substitution. |
| Go for backend | Using the default server with no timeouts or sharing mutable maps across handlers creates resource and race failures. | Set server read/write/idle timeouts, validate once at the boundary, and propagate request context. |
Interview and review notes
- Define the central abstraction without naming a library function.
- Trace one request, call, query, message, render, or state transition from input to observable result.
- Compare two alternatives from this chapter by guarantee, cost, and failure behavior.
- Explain the most likely production bug and the test or metric that reveals it.
- State what remains authoritative after process loss, retry, reconnect, or deployment.
Practice set
Easy
- Define every bold term in the concept tables in one precise sentence.
- Reproduce the focused examples and annotate the value or state after each important line.
- Explain the chapter progression diagram aloud in two minutes.
Medium
- Replace one convenient default with an explicit policy for validation, timeout, ordering, pagination, cleanup, or error handling.
- Write a negative test for each topic group.
- Compare the measured behavior before and after one justified change.
Hard
- Combine all topic groups into one thin vertical slice.
- Inject a realistic failure at the most important external boundary and prove recovery.
- Write a one-page design note covering ownership, trade-offs, security, observability, and rollback.
Chapter submission
Submit:
- source code or reproducible commands;
- automated tests plus one deliberately failing-before-fix test;
- captured output, query plan, trace, screenshot, or metric;
- a 300–500 word explanation of the execution flow and one rejected alternative;
- a short README with setup, versions, limitations, and cleanup steps.
- Continue with the Go gRPC Microservice project workshop.
Self-review rubric
| Dimension | Beginning | Competent | Professional |
|---|---|---|---|
| Explanation | Names APIs | Explains behavior | Connects guarantees, internals, and trade-offs |
| Implementation | Happy path only | Validated and tested | Clear ownership, failure recovery, and cleanup |
| Evidence | Manual claim | Repeatable output | Tests plus meaningful measurement or inspection |
| Communication | Steps missing | Reproducible README | Decisions, limits, and alternatives are explicit |
Roadmap coverage checklist
- To do: Go basics: types/structs/interfaces/embedding
- To do: Go basics: goroutines + channels (unbuffered/buffered/select/done pattern)
- To do: Go basics: defer/panic/recover
- To do: Go basics: error handling: errors.Is/As/wrapping
- To do: Go basics: packages + modules: go.mod/go.sum
- To do: Go for backend: net/http standard library handlers
- To do: Go for backend: gin framework: routing/middleware/binding/validation
- To do: Go for backend: database/sql + sqlx for PostgreSQL
- To do: Go for backend: gRPC: .proto file, service definition, unary + streaming
- To do: Go for backend: testing: TestXxx, table-driven tests, t.Parallel(), benchmarks
Quick revision
- Go basics: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Go for backend: connect the surface API to its guarantee, lifecycle, failure boundary, and evidence.
- Re-read the worked-example execution trace instead of memorizing isolated syntax.
- If you cannot name the owner of state and cleanup, the design is not yet complete.
Mastery check
How well can you recall this?
Finished this lesson?