all repos — piggy @ 83d9cee1226a9df3b762f3507bbb619f6004b5e9

Dead simple finance manager in Go, HTML and JS.

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 postRecords(w http.ResponseWriter, r *http.Request) {
82	var record app.Record
83	err := json.NewDecoder(r.Body).Decode(&record)
84	if err != nil {
85		log.Println("could not decode record JSON: " + err.Error())
86		new400Error(w, err)
87		return
88	}
89	err = app.DB.Save(&record).Error
90	if err != nil {
91		log.Println("could not save record: " + err.Error())
92		new500Error(w, err)
93		return
94	}
95
96	jsonResponse(w, record)
97}