Checkpoint 4
Web servers, tooling and databases, mixed with the core language and concurrency they rely on.
A handler calls w.Write([]byte("ok")) and then w.Header().Set("Content-Type", "text/plain"). What does the client get?
All questions with explanations (answers shown)
1. A handler calls
w.Write([]byte("ok"))and thenw.Header().Set("Content-Type", "text/plain"). What does the client get?Answer: The body, but without that header: headers are sent with the first write
The first
Writesends the status line and headers. Anything you set on the header map afterwards is ignored. Set headers first, thenWriteHeader, then the body.2. Why should a recover middleware not be your only protection against panics in a server that starts its own goroutines?
Answer: A
recoveronly catches a panic in its own goroutine, so a panic in a goroutine you started still crashes the processEach goroutine has its own stack, and
recoverworks only in a deferred call on the panicking goroutine. A goroutine you launch needs its owndeferwithrecover.3. You run
go get github.com/go-chi/chi/v5. Which files change?Answer:
go.mod(the requirement) andgo.sum(the checksums)go.modrecords the module and version you need, andgo.sumrecords checksums so every later download can be verified. Commit both.4. Package
orderimportsstore, and you add an import oforderinsidestore. What happens?Answer: The build fails with
import cycle not allowedGo compiles a package after the packages it imports, so imports must not form a circle. Move the shared type into a lower package, or have the lower package declare a small interface.
5. What does
db.QueryRow(...).Scan(&u.Name)return when no row matches?Answer:
sql.ErrNoRows, which you check witherrors.IsNo row is not a nil error.
QueryRowdefers the error toScan, which returnssql.ErrNoRows. Map it to a 404 in the handler, and treat other errors as a 500.6. Listing 20 orders and then running one query per order to load its customer is called what?
Answer: The N+1 query problem: fix it with a JOIN or one
WHERE id = ANY(...)queryOne query for the list plus N for the details. Each round trip costs time, so 21 queries can be far slower than 1 or 2. Load the related rows in one query.
7. net/http runs each request in its own goroutine. Your handlers share a
map[int]User. What do you need?Answer: A
sync.Mutex(orRWMutex) around every read and write of the mapPlain maps are not safe for concurrent writes; Go may stop the program with
concurrent map writes. Guard the map with a mutex, or keep the data in a database.8. Inside a handler, which context should you pass to
db.QueryContext?Answer:
r.Context(), so the query is cancelled when the client goes awayr.Context()ends when the client disconnects or the server shuts down. Passing it lets the driver cancel the query and free the connection.9. A struct has
Password stringjson:"-"`andEmail stringjson:"email,omitempty". You marshal it withEmail: ""`. What is in the JSON?Answer: Neither field
json:"-"never writes the field, andomitemptydrops the empty string. Neither key appears.10. Your store returns
fmt.Errorf("get user %d: %w", id, ErrNotFound). How does the handler decide to send a 404?Answer:
errors.Is(err, ErrNotFound)%wwraps the sentinel, so==fails buterrors.Isfollows the chain and finds it. Comparing message strings breaks the moment someone rewords the error.