-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
196 lines (162 loc) · 4.08 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
190
191
192
193
194
195
196
package ledger
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"strconv"
_ "github.com/lib/pq"
)
var (
db *sql.DB
connectionName = os.Getenv("POSTGRES_INSTANCE_CONNECTION_NAME")
dbUser = os.Getenv("POSTGRES_USER")
dbPassword = os.Getenv("POSTGRES_PASSWORD")
dsn = fmt.Sprintf("user=%s password=%s host=/cloudsql/%s", dbUser, dbPassword, connectionName)
)
func init() {
var err error
db, err = sql.Open("postgres", dsn)
if err != nil {
log.Fatalf("Could not open db: %v", err)
}
// Only allow 1 connection to the database to avoid overloading it.
db.SetMaxIdleConns(1)
db.SetMaxOpenConns(1)
}
func Balance(w http.ResponseWriter, req *http.Request) {
query := req.URL.Query()
username := query.Get("username")
account := findAccount(username)
fmt.Fprint(w, account.Balance)
}
// Account domain object ledger
type Account struct {
QualifiedUsername string
Balance float64
}
func Deposit(w http.ResponseWriter, req *http.Request) {
query := req.URL.Query()
username := query.Get("username")
amount := query.Get("amount")
/** converting the str1 variable into an int using Atoi method */
i1, err := strconv.Atoi(amount)
if err != nil {
panic(err)
}
balance, er := doTransaction(username, i1)
if er != nil {
switch err.(type) {
case *ErrUserNotFound:
tryCreatingAccount(username)
balanceAgain, _ := doTransaction(username, i1)
fmt.Fprint(w, balanceAgain)
return
default:
fmt.Fprint(w, "Oops! Something techy happened!!")
}
} else {
fmt.Fprint(w, balance)
}
}
func Withdraw(w http.ResponseWriter, req *http.Request) {
query := req.URL.Query()
username := query.Get("username")
amount := query.Get("amount")
i1, err := strconv.Atoi(amount)
if err != nil {
panic(err)
}
//negate the amount received in the request
i1 = i1 * -1
balance, err := doTransaction(username, i1)
if err != nil {
switch err.(type) {
case *ErrUserNotFound:
tryCreatingAccount(username)
balanceAgain, _ := doTransaction(username, i1)
fmt.Fprint(w, balanceAgain)
return
case *ErrInsufficientFunds:
fmt.Fprint(w, "Insufficient Funds")
return
default:
fmt.Fprint(w, "Oops! Something techy happened!!")
}
} else {
fmt.Fprint(w, balance)
}
}
func tryCreatingAccount(qualifiedUsername string) {
sqlStatement := `
INSERT INTO account (qualified_username, balance)
VALUES ($1, $2)`
_, err := db.Exec(sqlStatement, qualifiedUsername, 1000)
if err != nil {
panic(err)
}
}
func doTransaction(qualifiedUsername string, amount int) (float64, error) {
acc := findAccount(qualifiedUsername)
if acc == nil {
return 0, NewErrUserNotFound("User not found")
}
sqlStatement := `
UPDATE account
SET balance = balance + $1
WHERE qualified_username = $2 AND balance + $3 >= 0;`
res, err := db.Exec(sqlStatement, amount, qualifiedUsername, amount)
if err != nil {
panic(err)
}
count, err := res.RowsAffected()
if err != nil {
panic(err)
}
if count == 0 {
return 0, NewErrInsufficientFunds("Insufficient funds")
}
acc = findAccount(qualifiedUsername)
return acc.Balance, nil
}
func findAccount(qualifiedUsername string) *Account {
sqlStatement := `SELECT qualified_username,balance FROM account WHERE qualified_username=$1;`
acc := new(Account)
row := db.QueryRow(sqlStatement, qualifiedUsername)
err := row.Scan(&acc.QualifiedUsername, &acc.Balance)
switch err {
case sql.ErrNoRows:
return nil
case nil:
return acc
default:
panic(err)
}
}
//ErrUserNotFound model for user not found
type ErrUserNotFound struct {
message string
}
//NewErrUserNotFound function for User not found
func NewErrUserNotFound(message string) *ErrUserNotFound {
return &ErrUserNotFound{
message: message,
}
}
func (e *ErrUserNotFound) Error() string {
return e.message
}
//ErrInsufficientFunds model for insufficient funds
type ErrInsufficientFunds struct {
message string
}
//NewErrInsufficientFunds function for insufficient funds
func NewErrInsufficientFunds(message string) *ErrInsufficientFunds {
return &ErrInsufficientFunds{
message: message,
}
}
func (e *ErrInsufficientFunds) Error() string {
return e.message
}