src/api/api.go (view raw)
1package api
2
3import (
4 "encoding/json"
5 "log"
6 "net/http"
7
8 "github.com/BiRabittoh/piggy/src/app"
9)
10
11func getBookmakers(w http.ResponseWriter, r *http.Request) {
12 var bookmakers []app.Bookmaker
13 err := app.DB.Find(&bookmakers).Error
14 if err != nil {
15 log.Println("could not get bookmakers: " + err.Error())
16 new500Error(w, err)
17 return
18 }
19
20 jsonResponse(w, bookmakers)
21}
22
23func postBookmakers(w http.ResponseWriter, r *http.Request) {
24 var bookmaker app.Bookmaker
25 err := json.NewDecoder(r.Body).Decode(&bookmaker)
26 if err != nil {
27 log.Println("could not decode bookmaker JSON: " + err.Error())
28 new400Error(w, err)
29 return
30 }
31 err = app.DB.Save(&bookmaker).Error
32 if err != nil {
33 log.Println("could not save bookmaker: " + err.Error())
34 new500Error(w, err)
35 return
36 }
37
38 jsonResponse(w, bookmaker)
39}
40
41func getAccounts(w http.ResponseWriter, r *http.Request) {
42 var accounts []app.Account
43 err := app.DB.Find(&accounts).Error
44 if err != nil {
45 log.Println("could not get accounts: " + err.Error())
46 new500Error(w, err)
47 return
48 }
49
50 jsonResponse(w, accounts)
51}
52
53func postAccounts(w http.ResponseWriter, r *http.Request) {
54 var account app.Account
55 err := json.NewDecoder(r.Body).Decode(&account)
56 if err != nil {
57 log.Println("could not decode account JSON: " + err.Error())
58 new400Error(w, err)
59 return
60 }
61 err = app.DB.Save(&account).Error
62 if err != nil {
63 log.Println("could not save account: " + err.Error())
64 new500Error(w, err)
65 return
66 }
67
68 jsonResponse(w, account)
69}
70
71func getRecords(w http.ResponseWriter, r *http.Request) {
72 records, _, err := app.GetRecords()
73 if err != nil {
74 log.Println("could not get records: " + err.Error())
75 new500Error(w, err)
76 }
77
78 jsonResponse(w, records)
79}
80
81func getRecordsId(w http.ResponseWriter, r *http.Request) {
82 id, err := getId(r)
83 if err != nil {
84 new400Error(w, err)
85 return
86 }
87
88 record, err := app.GetRecord(id)
89 if err != nil {
90 log.Println("could not get record: " + err.Error())
91 new500Error(w, err)
92 }
93
94 jsonResponse(w, record)
95}
96
97func postRecords(w http.ResponseWriter, r *http.Request) {
98 var record app.Record
99 err := json.NewDecoder(r.Body).Decode(&record)
100 if err != nil {
101 log.Println("could not decode record JSON: " + err.Error())
102 new400Error(w, err)
103 return
104 }
105 err = app.DB.Save(&record).Error
106 if err != nil {
107 log.Println("could not save record: " + err.Error())
108 new500Error(w, err)
109 return
110 }
111
112 jsonResponse(w, record)
113}