-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
77 lines (66 loc) · 1.6 KB
/
api.go
File metadata and controls
77 lines (66 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"encoding/json"
"fmt"
"log/slog"
"net/http"
)
type API struct {
log *slog.Logger
db *DB
}
func (a *API) Health(w http.ResponseWriter, r *http.Request) {
// TODO: Health check
a.log.Info("Health", "remote", r.RemoteAddr)
fmt.Fprintln(w, "OK")
}
func (a *API) Add(w http.ResponseWriter, r *http.Request) {
var rd Ride
if err := json.NewDecoder(r.Body).Decode(&rd); err != nil {
a.log.Error("decode", "error", err)
http.Error(w, "bad record", http.StatusBadRequest)
return
}
if err := rd.Validate(); err != nil {
a.log.Error("validate", "error", err)
http.Error(w, "bad record", http.StatusBadRequest)
return
}
if err := a.db.Insert(rd); err != nil {
a.log.Error("insert", "error", err)
http.Error(w, "can't insert", http.StatusInternalServerError)
return
}
a.log.Info("added", "id", rd.ID)
resp := map[string]any{
"id": rd.ID,
}
a.sendJSON(w, resp)
}
func (a *API) Get(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "" {
http.Error(w, "missing ID", http.StatusBadRequest)
return
}
rd, err := a.db.Get(id)
if err != nil {
a.log.Error("scan", "error", err)
http.Error(w, "can't get rides", http.StatusInternalServerError)
return
}
resp := map[string]any{
"id": rd.ID,
"distance": rd.DistanceKM,
"shared": rd.Shared,
"price": RidePrice(rd.DistanceKM, rd.Shared),
}
a.sendJSON(w, resp)
}
func (a *API) sendJSON(w http.ResponseWriter, resp any) {
w.Header().Set("content-type", "application/json")
if err := json.NewEncoder(w).Encode(resp); err != nil {
a.log.Error("encode", "error", err)
return
}
}