/
main.go
101 lines (80 loc) · 2.44 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
/*
Exposes API endpoints to perform CRUD operations on Product entities.
*/
package main
import (
"api_product/domain"
"api_product/inventory"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
var _ []domain.Product = inventory.Bootstrap()
func addProduct(c *gin.Context) {
var newProduct domain.Product
if err := c.BindJSON(&newProduct); err != nil {
return
}
if inventory.Exists(newProduct) {
c.IndentedJSON(http.StatusConflict, "product already exists")
return
} else {
_ = inventory.Add(newProduct)
c.IndentedJSON(http.StatusAccepted, newProduct)
}
}
func getProductByID(c *gin.Context) {
id := c.Param("id")
product, error := inventory.GetInvetoryByID(id)
if error != nil {
message := fmt.Sprintf("Product id: %s, was not found", id)
c.IndentedJSON(http.StatusNotFound, message)
} else {
c.IndentedJSON(http.StatusOK, product)
}
}
func getProducts(c *gin.Context) {
c.IndentedJSON(http.StatusOK, inventory.List())
}
func deleteProduct(c *gin.Context) {
id := c.Param("id")
for index, product := range inventory.List() {
if product.ID == id {
_ = inventory.Remove(index)
message := fmt.Sprintf("Product id: %s, has been deleted", product.ID)
c.IndentedJSON(http.StatusAccepted, message)
return
}
}
message := fmt.Sprintf("Product id: %s, was not found ", id)
c.IndentedJSON(http.StatusNotFound, message)
}
func updateProduct(c *gin.Context) {
var patch domain.Product
if err := c.BindJSON(&patch); err != nil {
return
}
_, error := inventory.GetInvetoryByID(patch.ID)
if error == nil {
// MARK: can we log the full representation of the product ?
product := inventory.Update(patch)
message := fmt.Sprintf("Product: %s, has been updated", product.ID)
c.IndentedJSON(http.StatusAccepted, message)
} else {
message := fmt.Sprintf("Product id: %s, was not found ", patch.ID)
c.IndentedJSON(http.StatusNotFound, message)
}
}
func setupRouter() *gin.Engine {
router := gin.Default()
router.GET("/products", getProducts)
router.GET("/product/:id", getProductByID)
router.POST("/product", addProduct)
router.PATCH("/product", updateProduct)
router.DELETE("product/:id", deleteProduct)
return router
}
func main() {
router := setupRouter()
router.Run(":7000")
}