Add lesson 4: Routing and middleware

Daniel Tanaka 1 year ago
parent ef93d0de64 commit 31324920054668345546e8d7db41ddb847f7478d
3 changed files with 47 additions and 0 deletions
+19-0lessons/04-routing-and-middleware/README.md ADDED
@@ -0,0 +1,19 @@
1+# Lesson 4: Routing and middleware
2+
3+We look at routing and middleware the way working developers use it, with examples you can change and run right away.
4+
5+Full lesson: [https://glibcode.net/courses/go-apis/lessons/4](https://glibcode.net/courses/go-apis/lessons/4)
6+
7+## Files
8+
9+- `main.go`: method patterns and a logging middleware
10+
11+## Run it
12+
13+```sh
14+go run ./lessons/04-routing-and-middleware
15+```
16+
17+## Exercises
18+
19+See [exercises.md](exercises.md). Ask in the forum once you've tried.
+5-0lessons/04-routing-and-middleware/exercises.md ADDED
@@ -0,0 +1,5 @@
1+# Exercises: lesson 4
2+
3+1. Add a comment above each block explaining what it does, in your own words.
4+2. What happens with an empty input? Change the code so it handles that case with a clear message.
5+3. Find one thing in `main.go` you could name better and rename it everywhere.
+23-0lessons/04-routing-and-middleware/main.go ADDED
@@ -0,0 +1,23 @@
1+package main
2+
3+import (
4+ "log"
5+ "net/http"
6+ "time"
7+)
8+
9+func logging(next http.Handler) http.Handler {
10+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
11+ start := time.Now()
12+ next.ServeHTTP(w, r)
13+ log.Printf("%s %s %s", r.Method, r.URL.Path, time.Since(start))
14+ })
15+}
16+
17+func main() {
18+ mux := http.NewServeMux()
19+ mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
20+ w.Write([]byte("user " + r.PathValue("id") + "\n"))
21+ })
22+ log.Fatal(http.ListenAndServe(":8080", logging(mux)))
23+}