Add lesson 3: JSON in and out

Daniel Tanaka 1 year ago
parent b43c939df3 commit ef93d0de64bfbebd207cc2cedb9a6d6dcd9d358f
3 changed files with 61 additions and 0 deletions
+19-0lessons/03-json-in-and-out/README.md ADDED
@@ -0,0 +1,19 @@
1+# Lesson 3: JSON in and out
2+
3+This lesson covers jSON in and out. You'll read a short explanation, try three small exercises and finish with a quiz.
4+
5+Full lesson: [https://glibcode.net/courses/go-apis/lessons/3](https://glibcode.net/courses/go-apis/lessons/3)
6+
7+## Files
8+
9+- `main.go`: encoding and decoding JSON
10+
11+## Run it
12+
13+```sh
14+go run ./lessons/03-json-in-and-out
15+```
16+
17+## Exercises
18+
19+See [exercises.md](exercises.md). Ask in the forum once you've tried.
+5-0lessons/03-json-in-and-out/exercises.md ADDED
@@ -0,0 +1,5 @@
1+# Exercises: lesson 3
2+
3+1. Combine this lesson with the previous one: use something from both in a small program of your own.
4+2. Break the example on purpose: delete a bracket or misspell a name. Read the error message. Which line does it point to?
5+3. Look up one function or command the example uses in the official documentation. Note one option you didn't know.
+37-0lessons/03-json-in-and-out/main.go ADDED
@@ -0,0 +1,37 @@
1+package main
2+
3+import (
4+ "encoding/json"
5+ "net/http"
6+)
7+
8+type Todo struct {
9+ ID int `json:"id"`
10+ Title string `json:"title"`
11+ Done bool `json:"done"`
12+}
13+
14+var todos = []Todo{{1, "Learn Go", true}, {2, "Ship it", false}}
15+
16+func list(w http.ResponseWriter, r *http.Request) {
17+ w.Header().Set("Content-Type", "application/json")
18+ json.NewEncoder(w).Encode(todos)
19+}
20+
21+func create(w http.ResponseWriter, r *http.Request) {
22+ var t Todo
23+ if err := json.NewDecoder(r.Body).Decode(&t); err != nil {
24+ http.Error(w, err.Error(), http.StatusBadRequest)
25+ return
26+ }
27+ t.ID = len(todos) + 1
28+ todos = append(todos, t)
29+ w.WriteHeader(http.StatusCreated)
30+ json.NewEncoder(w).Encode(t)
31+}
32+
33+func main() {
34+ http.HandleFunc("GET /todos", list)
35+ http.HandleFunc("POST /todos", create)
36+ http.ListenAndServe(":8080", nil)
37+}