8 months ago
39 lines847 B
package main | |
| |
import ( | |
"encoding/json" | |
"net/http" | |
) | |
| |
type Todo struct { | |
ID int `json:"id"` | |
Title string `json:"title"` | |
Done bool `json:"done"` | |
} | |
| |
var todos = []Todo{{1, "Learn Go", true}, {2, "Ship it", false}} | |
| |
func list(w http.ResponseWriter, r *http.Request) { | |
w.Header().Set("Content-Type", "application/json") | |
json.NewEncoder(w).Encode(todos) | |
} | |
| |
func create(w http.ResponseWriter, r *http.Request) { | |
var t Todo | |
if err := json.NewDecoder(r.Body).Decode(&t); err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
t.ID = len(todos) + 1 | |
todos = append(todos, t) | |
w.WriteHeader(http.StatusCreated) | |
json.NewEncoder(w).Encode(t) | |
} | |
| |
func main() { | |
http.HandleFunc("GET /todos", list) | |
http.HandleFunc("POST /todos", create) | |
http.ListenAndServe(":8080", nil) | |
} | |
| |
// This is the version we use in the video. |