@@ -17,27 +17,6 @@ func (a *API) Health(w http.ResponseWriter, r *http.Request) {
1717 fmt .Fprintln (w , "OK" )
1818}
1919
20- func (a * API ) Get (w http.ResponseWriter , r * http.Request ) {
21- id := r .PathValue ("id" )
22- if id == "" {
23- http .Error (w , "missing ID" , http .StatusBadRequest )
24- return
25- }
26-
27- rd , err := a .db .Get (id )
28- if err != nil {
29- a .log .Error ("scan" , "error" , err )
30- http .Error (w , "can't get rides" , http .StatusInternalServerError )
31- return
32- }
33-
34- w .Header ().Set ("content-type" , "application/json" )
35- if err := json .NewEncoder (w ).Encode (rd ); err != nil {
36- a .log .Error ("encode" , "error" , err )
37- return
38- }
39- }
40-
4120func (a * API ) Add (w http.ResponseWriter , r * http.Request ) {
4221 var rd Ride
4322 if err := json .NewDecoder (r .Body ).Decode (& rd ); err != nil {
@@ -57,8 +36,41 @@ func (a *API) Add(w http.ResponseWriter, r *http.Request) {
5736 http .Error (w , "can't insert" , http .StatusInternalServerError )
5837 return
5938 }
39+ a .log .Info ("added" , "id" , rd .ID )
6040
61- json . NewEncoder ( w ). Encode ( map [string ]any {
41+ resp := map [string ]any {
6242 "id" : rd .ID ,
63- })
43+ }
44+ a .sendJSON (w , resp )
45+ }
46+
47+ func (a * API ) Get (w http.ResponseWriter , r * http.Request ) {
48+ id := r .PathValue ("id" )
49+ if id == "" {
50+ http .Error (w , "missing ID" , http .StatusBadRequest )
51+ return
52+ }
53+
54+ rd , err := a .db .Get (id )
55+ if err != nil {
56+ a .log .Error ("scan" , "error" , err )
57+ http .Error (w , "can't get rides" , http .StatusInternalServerError )
58+ return
59+ }
60+
61+ resp := map [string ]any {
62+ "id" : rd .ID ,
63+ "distance" : rd .Distance ,
64+ "shared" : rd .Shared ,
65+ "price" : RidePrice (rd .Distance , rd .Shared ),
66+ }
67+ a .sendJSON (w , resp )
68+ }
69+
70+ func (a * API ) sendJSON (w http.ResponseWriter , resp any ) {
71+ w .Header ().Set ("content-type" , "application/json" )
72+ if err := json .NewEncoder (w ).Encode (resp ); err != nil {
73+ a .log .Error ("encode" , "error" , err )
74+ return
75+ }
6476}
0 commit comments