This repository was archived by the owner on Oct 5, 2019. It is now read-only.
forked from kyma-project/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorder-front.go
More file actions
158 lines (132 loc) · 4.22 KB
/
order-front.go
File metadata and controls
158 lines (132 loc) · 4.22 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
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
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
)
type Order struct {
OrderCode string `json:"orderCode"`
OrderPrice float64 `json:"orderPrice"`
}
type StoredOrder struct {
OrderId string `json:"orderId"`
Namespace string `json:"namespace"`
Total float64 `json:"total"`
}
var httpTransport *http.Transport
var httpClient *http.Client
func main() {
var (
port = flag.Int("port", 8080, "tcp port on which to listen for http requests")
dbUrl = flag.String("db-url", "", "db url to which store order data")
)
flag.Parse()
httpTransport = &http.Transport{}
httpClient = &http.Client{
Transport: httpTransport,
}
http.Handle("/orders", ordersHandler(dbUrl))
log.Printf("HTTP server starting on port %d", *port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), nil))
}
func ordersHandler(dbUrl *string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch requestMethod := &r.Method; *requestMethod {
case http.MethodPost:
if r.Body == nil {
http.Error(w, "Please send a CloudEvent in the HTTP request body", http.StatusBadRequest)
return
}
b, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
log.Printf("Error reading HTTP request body: %v", err)
http.Error(w, "Error reading HTTP request body", http.StatusBadRequest)
return
}
var order Order
if err := json.Unmarshal(b, &order); err != nil {
log.Printf("Error unmarshalling event data: %v", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
log.Println(r.Header)
if err := storeOrdersInDB(&order, dbUrl, r.Header); err != nil {
w.WriteHeader(http.StatusInternalServerError)
} else {
w.WriteHeader(http.StatusCreated)
}
case http.MethodGet:
orders, err := getOrdersFromDB(dbUrl, r.Header)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
} else {
json.NewEncoder(w).Encode(orders)
}
case http.MethodDelete:
statusCode, err := deleteOrdersFromDB(dbUrl, r.Header)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
} else {
w.WriteHeader(statusCode)
}
default:
http.Error(w, fmt.Sprintf("HTTP method '%v' is not supported", *requestMethod), http.StatusMethodNotAllowed)
}
})
}
func getOrdersFromDB(dbUrl *string, incomingHeaders http.Header) (*[]StoredOrder, error) {
downstreamRequest, err := http.NewRequest(http.MethodGet, *dbUrl, nil)
propagateTracingHeaders(incomingHeaders, downstreamRequest)
resp, err := httpClient.Do(downstreamRequest)
if err != nil {
return nil, err
}
orders := make([]StoredOrder, 0)
byteArray, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
json.Unmarshal(byteArray, &orders)
return &orders, nil
}
func deleteOrdersFromDB(dbUrl *string, incomingHeaders http.Header) (int, error) {
downstreamRequest, err := http.NewRequest(http.MethodDelete, *dbUrl, nil)
propagateTracingHeaders(incomingHeaders, downstreamRequest)
resp, err := httpClient.Do(downstreamRequest)
if err != nil {
return -1, err
}
return resp.StatusCode, nil
}
func storeOrdersInDB(order *Order, dbUrl *string, incomingHeaders http.Header) error {
toSend := StoredOrder{OrderId: order.OrderCode, Total: order.OrderPrice}
payload, err := json.Marshal(toSend)
if err != nil {
return err
}
downstreamRequest, err := http.NewRequest(http.MethodPost, *dbUrl, bytes.NewBuffer(payload))
downstreamRequest.Header.Add("Content-Type", "application/json")
propagateTracingHeaders(incomingHeaders, downstreamRequest)
resp, err := httpClient.Do(downstreamRequest)
statusCode := resp.StatusCode
if statusCode >= 399 && statusCode != 409 {
return errors.New("error status when storing event")
}
return err
}
func propagateTracingHeaders(incomingHeaders http.Header, downstreamRequest *http.Request) {
traceHeadersName := [...]string{"X-Request-Id", "X-B3-Traceid", "X-B3-Spanid", "X-B3-Parentspanid", "X-B3-Sampled", "X-B3-Flags", "X-Ot-Span-Context"}
for _, headerName := range traceHeadersName {
headerVal := incomingHeaders[headerName]
if headerVal != nil && len(headerVal) > 0 {
log.Print(headerName, headerVal)
downstreamRequest.Header[headerName] = headerVal
}
}
}