-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
92 lines (76 loc) · 1.75 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
package main
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
"gitlab.com/erikurbanski/desafio1-full-cycle/models"
)
type AddAccountRequestBody struct {
Number string `json:"account_number"`
Amount float64 `json:"amount"`
}
type TransferAccountRequestBody struct {
From string `json:"from"`
To string `json:"to"`
Amount float64 `json:"amount"`
}
func main() {
err := models.ConnectDatabase()
checkErr(err)
r := gin.Default()
router := r.Group("/bank-accounts")
{
router.POST("/", createAccount)
router.POST("/transfer", transfer)
router.GET("/", getAllAccounts)
}
r.Run(":8000")
}
func createAccount(c *gin.Context) {
body := AddAccountRequestBody{}
if err := c.BindJSON(&body); err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
var account models.Account
account.Number = body.Number
account.Amount = body.Amount
accountId := models.InsertAccount(account)
if accountId == 0 {
c.JSON(404, gin.H{"error": "Insert error!"})
} else {
c.JSON(http.StatusCreated, accountId)
}
}
func transfer(c *gin.Context) {
body := TransferAccountRequestBody{}
if err := c.BindJSON(&body); err != nil {
c.AbortWithError(http.StatusBadRequest, err)
return
}
var transfer models.Transfer
transfer.From = body.From
transfer.To = body.To
transfer.Amount = body.Amount
msg := models.TransferValues(transfer)
if msg != "" {
c.JSON(200, gin.H{"message": msg})
} else {
c.JSON(404, gin.H{"error": "Transfer error!"})
}
}
func getAllAccounts(c *gin.Context) {
accounts, err := models.GetAccounts()
checkErr(err)
if accounts == nil {
c.JSON(404, gin.H{"error": "No records found!"})
return
} else {
c.JSON(200, gin.H{"data": accounts})
}
}
func checkErr(err error) {
if err != nil {
log.Fatal(err)
}
}