forked from ketyung/simpleapi_go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
91 lines (61 loc) · 1.51 KB
/
main.go
File metadata and controls
91 lines (61 loc) · 1.51 KB
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
package main
import (
"simpleapi_go/models"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/products", getProducts)
router.GET("/product/:code", getProduct)
router.POST("/products", addProduct)
router.Run("localhost:8083")
}
/*
// curl command to get all products
curl http://localhost:8083/products \
--include \
--header "Content-Type: application/json" \
--request "GET"
*/
func getProducts(c *gin.Context) {
products := models.GetProducts()
if products == nil || len(products) == 0 {
c.AbortWithStatus(http.StatusNotFound)
} else {
c.IndentedJSON(http.StatusOK, products)
}
}
/*
// curl command to get a product by code
curl http://localhost:8083/product/P0111 \
--include \
--header "Content-Type: application/json" \
--request "GET"
*/
func getProduct(c *gin.Context) {
code := c.Param("code")
product := models.GetProduct(code)
if product == nil {
c.AbortWithStatus(http.StatusNotFound)
} else {
c.IndentedJSON(http.StatusOK, product)
}
}
/*
// e.g. curl command to test adding a new product
curl http://localhost:8083/products \
--include \
--header "Content-Type: application/json" \
--request "POST" \
--data '{"code": "P1114","name": "MacBook Air M1","qty": 10}'
*/
func addProduct(c *gin.Context) {
var prod models.Product
if err := c.BindJSON(&prod); err != nil {
c.AbortWithStatus(http.StatusBadRequest)
} else {
models.AddProduct(prod)
c.IndentedJSON(http.StatusCreated, prod)
}
}