-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
277 lines (215 loc) · 6.32 KB
/
app.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
package main
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"log"
"net"
"net/http"
"strconv"
"github.com/gteca/bank-app/db"
"github.com/gteca/bank-app/operations"
_ "github.com/go-sql-driver/mysql"
"github.com/google/uuid"
"github.com/gorilla/mux"
"google.golang.org/grpc"
)
const (
DBNAME = "bankOfAmerica"
DBUSER = "root"
DBPASSWD = "fakebank1234"
)
type Api struct {
Router *mux.Router
DB *sql.DB
}
type Grpc struct {
operations.UnimplementedOperationsServer
DB *sql.DB
}
const (
GRPC_SUCCESS = "Success"
GRPC_NO_USER_FOUND = "No User with such credit card found"
GRPC_INTERNAL_SERVER_ERROR = "Internal Server Error"
)
func InitDB() (*sql.DB, error) {
connectionInfo := fmt.Sprintf("%v:%v@tcp(127.0.0.1:3306)/%v", DBUSER, DBPASSWD, DBNAME)
var err error
db, err := sql.Open("mysql", connectionInfo)
if err != nil {
return nil, err
}
return db, nil
}
func (server *Grpc) InitGrpcServer() {
dbConn, err := InitDB()
if err != nil {
log.Println("Error closing database:", err)
}
server.DB = dbConn
}
func (api *Api) InitApiServer() error {
dbConn, err := InitDB()
if err != nil {
log.Println("Error closing database:", err)
}
api.DB = dbConn
api.Router = mux.NewRouter().StrictSlash(true)
api.HandleRoutes()
return nil
}
func (api *Api) RunApiServer(ipPort string) {
log.Printf("API Server listening on %v", ipPort)
log.Fatal(http.ListenAndServe(ipPort, api.Router))
}
func (server *Grpc) RunGrpcServer(ipPort string) {
log.Printf("GRPC Server listening on %v", ipPort)
listener, err := net.Listen("tcp", ipPort)
if err != nil {
log.Fatalf("Error: %v - Failed to listen on : %v", err, ipPort)
}
grpcServer := grpc.NewServer()
operations.RegisterOperationsServer(grpcServer, server)
log.Fatal(grpcServer.Serve(listener))
}
func (server *Grpc) ExecutePayment(ctx context.Context, payment *operations.PaymentReq) (*operations.PaymentResp, error) {
log.Printf("Received transaction request for amount: %v for card: %s", payment.Amount, payment.CardNumber)
transactionId := uuid.New().String()
account, result := server.getAccountByCardNumber(payment.CardNumber)
if result != GRPC_SUCCESS {
log.Printf("Failed to retrieve account for CardNumber: %s", payment.CardNumber)
return &operations.PaymentResp{
Success: false,
TransactionId: transactionId,
}, errors.New(result)
}
proceed := server.HasSufficientBalance(account.Balance, payment.Amount)
log.Printf("Proceed: %v", proceed)
if !proceed {
log.Printf("proceed? %v", proceed)
return &operations.PaymentResp{
Success: false,
TransactionId: transactionId,
}, errors.New("User has no sufficient funds")
}
account.Balance -= payment.Amount
if err := db.UpdateAccount(server.DB, &account); err != nil {
return &operations.PaymentResp{
Success: false,
TransactionId: transactionId,
}, err
}
return &operations.PaymentResp{
Success: true,
TransactionId: transactionId,
}, nil
}
func (server *Grpc) getAccountByCardNumber(cardNumber string) (db.Account, string) {
account, err := db.GetAccountByCardNumber(server.DB, cardNumber)
var result string
if err != nil {
switch err {
case sql.ErrNoRows:
result = GRPC_NO_USER_FOUND
default:
result = GRPC_INTERNAL_SERVER_ERROR
}
}
result = GRPC_SUCCESS
return account, result
}
func (server *Grpc) HasSufficientBalance(balance float32, amount float32) bool {
return balance-amount > 0.0
}
func sendResponse(w http.ResponseWriter, statusCode int, payload interface{}) {
response, _ := json.Marshal(payload)
w.Header().Set("Content-type", "application/json")
w.WriteHeader(statusCode)
w.Write(response)
}
func sendError(w http.ResponseWriter, statusCode int, err string) {
error_msg := map[string]string{"error": err}
sendResponse(w, statusCode, error_msg)
}
func (api *Api) getAccounts(w http.ResponseWriter, r *http.Request) {
accounts, err := db.GetAccounts(api.DB)
if err != nil {
sendError(w, http.StatusInternalServerError, err.Error())
return
}
sendResponse(w, http.StatusOK, accounts)
}
func (api *Api) getAccountByID(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
sendError(w, http.StatusInternalServerError, "Cannot parse user id")
}
account, err := db.GetAccountByID(api.DB, id)
if err != nil {
switch err {
case sql.ErrNoRows:
sendError(w, http.StatusBadRequest, "User not found")
default:
sendError(w, http.StatusInternalServerError, err.Error())
}
return
}
sendResponse(w, http.StatusOK, account)
}
func (api *Api) createAccount(w http.ResponseWriter, r *http.Request) {
var account db.Account
err := json.NewDecoder(r.Body).Decode(&account)
if err != nil {
sendError(w, http.StatusBadRequest, err.Error())
return
}
err = db.CreateAccount(api.DB, &account)
if err != nil {
sendError(w, http.StatusInternalServerError, err.Error())
return
}
sendResponse(w, http.StatusCreated, account)
}
func (api *Api) updateAccount(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
sendError(w, http.StatusInternalServerError, "Cannot parse user id")
}
var account db.Account
err = json.NewDecoder(r.Body).Decode(&account)
if err != nil {
sendError(w, http.StatusBadRequest, err.Error())
return
}
account.Id = id
err = db.UpdateAccount(api.DB, &account)
if err != nil {
sendError(w, http.StatusInternalServerError, err.Error())
return
}
sendResponse(w, http.StatusNoContent, account)
}
func (api *Api) deleteAccount(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
sendError(w, http.StatusInternalServerError, "Cannot parse user id")
}
err = db.DeleteAccount(api.DB, id)
if err != nil {
sendError(w, http.StatusInternalServerError, err.Error())
return
}
sendResponse(w, http.StatusOK, map[string]string{"result": "successful deletion"})
}
func (api *Api) HandleRoutes() {
api.Router.HandleFunc("/account", api.getAccounts).Methods("GET")
api.Router.HandleFunc("/account/{id}", api.getAccountByID).Methods("GET")
api.Router.HandleFunc("/account", api.createAccount).Methods("POST")
api.Router.HandleFunc("/account/{id}", api.updateAccount).Methods("PUT")
api.Router.HandleFunc("/account/{id}", api.deleteAccount).Methods("DELETE")
}