forked from Securing-DevOps/invoicer-chapter2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
189 lines (173 loc) · 5.22 KB
/
main.go
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Contributor: Julien Vehent jvehent@mozilla.com [:ulfr]
package main
//go:generate ./version.sh
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"time"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type invoicer struct {
db *gorm.DB
}
func main() {
var (
iv invoicer
err error
)
var db *gorm.DB
if os.Getenv("INVOICER_USE_POSTGRES") != "" {
log.Println("Opening postgres connection")
db, err = gorm.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=%s",
os.Getenv("INVOICER_POSTGRES_USER"),
os.Getenv("INVOICER_POSTGRES_PASSWORD"),
os.Getenv("INVOICER_POSTGRES_HOST"),
os.Getenv("INVOICER_POSTGRES_DB"),
os.Getenv("INVOICER_POSTGRES_SSLMODE"),
))
} else {
log.Println("Opening sqlite connection")
db, err = gorm.Open("sqlite3", "invoicer.db")
}
if err != nil {
panic("failed to connect database")
}
iv.db = db
iv.db.AutoMigrate(&Invoice{}, &Charge{})
iv.db.LogMode(true)
// register routes
r := mux.NewRouter()
r.HandleFunc("/__heartbeat__", getHeartbeat).Methods("GET")
r.HandleFunc("/invoice/{id:[0-9]+}", iv.getInvoice).Methods("GET")
r.HandleFunc("/invoice", iv.postInvoice).Methods("POST")
r.HandleFunc("/invoice/{id:[0-9]+}", iv.putInvoice).Methods("PUT")
r.HandleFunc("/invoice/{id:[0-9]+}", iv.deleteInvoice).Methods("DELETE")
r.HandleFunc("/__version__", getVersion).Methods("GET")
// all set, start the http handler
log.Fatal(http.ListenAndServe(":8080", r))
}
type Invoice struct {
gorm.Model
IsPaid bool `json:"is_paid"`
Amount int `json:"amount"`
PaymentDate time.Time `json:"payment_date"`
DueDate time.Time `json:"due_date"`
Charges []Charge `json:"charges"`
}
type Charge struct {
gorm.Model
InvoiceID int `gorm:"index" json:"invoice_id"`
Type string `json:"type"`
Amount float64 `json:"amount"`
Description string `json:"description"`
}
func (iv *invoicer) getInvoice(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
log.Println("getting invoice id", vars["id"])
var i1 Invoice
id, _ := strconv.Atoi(vars["id"])
iv.db.First(&i1, id)
fmt.Printf("%+v\n", i1)
if i1.ID == 0 {
httpError(w, http.StatusNotFound, "No invoice id %s", vars["id"])
return
}
iv.db.Where("invoice_id = ?", i1.ID).Find(&i1.Charges)
jsonInvoice, err := json.Marshal(i1)
if err != nil {
httpError(w, http.StatusInternalServerError, "failed to retrieve invoice id %d: %s", vars["id"], err)
return
}
w.WriteHeader(http.StatusOK)
w.Write(jsonInvoice)
}
func (iv *invoicer) postInvoice(w http.ResponseWriter, r *http.Request) {
log.Println("posting new invoice")
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
var i1 Invoice
err = json.Unmarshal(body, &i1)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to parse request body: %s", err)
return
}
// make sure the IDs are null before inserting
i1.ID = 0
for i := 0; i < len(i1.Charges); i++ {
i1.Charges[i].ID = 0
i1.Charges[i].InvoiceID = 0
}
iv.db.Create(&i1)
iv.db.Last(&i1)
log.Printf("%+v\n", i1)
w.WriteHeader(http.StatusCreated)
w.Write([]byte(fmt.Sprintf("created invoice %d", i1.ID)))
}
func (iv *invoicer) putInvoice(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
log.Println("updating invoice", vars["id"])
var i1 Invoice
iv.db.First(&i1, vars["id"])
if i1.ID == 0 {
httpError(w, http.StatusNotFound, "No invoice id %s", vars["id"])
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
err = json.Unmarshal(body, &i1)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to parse request body: %s", err)
return
}
iv.db.Save(&i1)
iv.db.First(&i1, vars["id"])
log.Printf("%+v\n", i1)
w.WriteHeader(http.StatusAccepted)
w.Write([]byte(fmt.Sprintf("updated invoice %d", i1.ID)))
}
func (iv *invoicer) deleteInvoice(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
log.Println("deleting invoice", vars["id"])
var i1 Invoice
id, _ := strconv.Atoi(vars["id"])
iv.db.Where("invoice_id = ?", id).Delete(Charge{})
i1.ID = uint(id)
iv.db.Delete(&i1)
w.WriteHeader(http.StatusAccepted)
w.Write([]byte(fmt.Sprintf("deleted invoice %d", i1.ID)))
}
func getHeartbeat(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("I am alive"))
}
// handleVersion returns the current version of the API
func getVersion(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(fmt.Sprintf(`{
"source": "https://github.com/Securing-DevOps/invoicer",
"version": "%s",
"commit": "%s",
"build": "https://circleci.com/gh/Securing-DevOps/invoicer/"
}`, version, commit)))
}
func httpError(w http.ResponseWriter, errorCode int, errorMessage string, args ...interface{}) {
log.Printf("%d: %s", errorCode, fmt.Sprintf(errorMessage, args...))
http.Error(w, fmt.Sprintf(errorMessage, args...), errorCode)
return
}