@@ -3,16 +3,39 @@ package routes
3
3
import (
4
4
"encoding/json"
5
5
"io/ioutil"
6
+ "log"
6
7
"net/http"
7
8
)
8
9
10
+ type Item struct {
11
+ Name string `json:"name"`
12
+ Quantity int `json:"quantity"`
13
+ Price int `json:"price"`
14
+ Id float32 `json:"id"`
15
+ }
16
+
17
+ type ItemListPrice struct {
18
+ Items []Item `json:"item"`
19
+ Total int `json:"total"`
20
+ }
21
+
22
+ var itemsBunch ItemListPrice
23
+
9
24
func add (w http.ResponseWriter , r * http.Request ) {
10
25
w .Header ().Set ("Content-Type" , "application/json; charset=UTF-8" )
11
26
12
27
if r .Method == "POST" {
13
28
w .WriteHeader (http .StatusOK )
14
29
bodyBytes , _ := ioutil .ReadAll (r .Body )
15
- if err := json .NewEncoder (w ).Encode (bodyBytes ); err != nil {
30
+ var element Item
31
+ err := json .Unmarshal (bodyBytes , & element )
32
+ if err != nil {
33
+ log .Println ("error:" , err )
34
+ }
35
+ itemsBunch .Items = append (itemsBunch .Items , element )
36
+ totalProduct := productTotalPrice (element .Price , element .Quantity )
37
+ itemsBunch .Total = newTotal (itemsBunch .Total , totalProduct )
38
+ if err := json .NewEncoder (w ).Encode (itemsBunch ); err != nil {
16
39
panic (err )
17
40
}
18
41
} else {
@@ -31,3 +54,11 @@ func delete(w http.ResponseWriter, r *http.Request) {
31
54
// ..
32
55
33
56
}
57
+
58
+ func newTotal (total , newElement int ) int {
59
+ return total + newElement
60
+ }
61
+
62
+ func productTotalPrice (productPrice , quantity int ) int {
63
+ return productPrice * quantity
64
+ }
0 commit comments