Add lesson 7: Context and timeouts

Daniel Tanaka 11 months ago
parent bc51da4a22 commit 11562b3d581d49994ec7fdb93b5d039573f76103
3 changed files with 57 additions and 0 deletions
+19-0lessons/07-context-and-timeouts/README.md ADDED
@@ -0,0 +1,19 @@
1+# Lesson 7: Context and timeouts
2+
3+In this lesson you'll work through context and timeouts step by step, with short exercises after each idea.
4+
5+Full lesson: [https://glibcode.net/courses/go-apis/lessons/7](https://glibcode.net/courses/go-apis/lessons/7)
6+
7+## Files
8+
9+- `main.go`: a request context with a deadline
10+
11+## Run it
12+
13+```sh
14+go run ./lessons/07-context-and-timeouts
15+```
16+
17+## Exercises
18+
19+See [exercises.md](exercises.md). Ask in the forum once you've tried.
+5-0lessons/07-context-and-timeouts/exercises.md ADDED
@@ -0,0 +1,5 @@
1+# Exercises: lesson 7
2+
3+1. Rewrite the main part so it runs twice with two different inputs, without copying the code.
4+2. Add a comment above each block explaining what it does, in your own words.
5+3. Find one thing in `main.go` you could name better and rename it everywhere.
+33-0lessons/07-context-and-timeouts/main.go ADDED
@@ -0,0 +1,33 @@
1+package main
2+
3+import (
4+ "context"
5+ "fmt"
6+ "net/http"
7+ "time"
8+)
9+
10+func slowReport(ctx context.Context) (string, error) {
11+ select {
12+ case <-time.After(3 * time.Second):
13+ return "report ready", nil
14+ case <-ctx.Done():
15+ return "", ctx.Err()
16+ }
17+}
18+
19+func handler(w http.ResponseWriter, r *http.Request) {
20+ ctx, cancel := context.WithTimeout(r.Context(), time.Second)
21+ defer cancel()
22+ msg, err := slowReport(ctx)
23+ if err != nil {
24+ http.Error(w, err.Error(), http.StatusGatewayTimeout)
25+ return
26+ }
27+ fmt.Fprintln(w, msg)
28+}
29+
30+func main() {
31+ http.HandleFunc("/report", handler)
32+ http.ListenAndServe(":8080", nil)
33+}