-
Notifications
You must be signed in to change notification settings - Fork 0
/
marshaling.go
131 lines (111 loc) · 2.63 KB
/
marshaling.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
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
package handler
import (
"fmt"
"io/ioutil"
"mime"
"net/http"
"strings"
api "github.com/HailoOSS/api-proxy/proto/api"
"github.com/HailoOSS/platform/errors"
"github.com/HailoOSS/protobuf/proto"
)
const (
hob = "hob"
city = "city"
sessionId = "session_id"
apiToken = "api_token"
)
var (
passHeaders = map[string]bool{"Authorization": true}
)
func httpRequestToProto(r *http.Request) (*api.Request, errors.Error) {
protoReq := &api.Request{
Path: proto.String(r.URL.Path),
Verb: proto.String(r.Method),
Get: make([]*api.Request_Pair, 0),
Post: make([]*api.Request_Pair, 0),
Header: make([]string, 0),
}
// Not all clients send the correct mime type. Add it if it's missing
var ct string
if r.Method == "POST" || r.Method == "PUT" {
var err error
ct, _, err = mime.ParseMediaType(r.Header.Get("Content-Type"))
if ct == "" || err != nil {
ct = formEncodedMime
r.Header.Set("Content-Type", ct)
}
}
if r.Body != nil && ct != formEncodedMime {
reqBytes, _ := ioutil.ReadAll(r.Body)
protoReq.Body = proto.String(string(reqBytes))
}
// Get GET, POST or PUT parameters
if r.Body != nil {
err := r.ParseForm()
if err != nil {
return nil, errors.BadRequest(
"11",
fmt.Sprintf("Problem parsing HTTP request parameters: %v", err),
)
}
}
hobCode := ""
for k, vs := range r.URL.Query() {
if k == sessionId || k == apiToken {
continue
}
switch k {
case hob:
hobCode = vs[0]
continue
case city:
if len(vs[0]) == 3 && len(hobCode) != 3 {
hobCode = vs[0]
}
}
// pick first v
protoReq.Get = append(protoReq.Get, &api.Request_Pair{
Key: proto.String(k),
Value: proto.String(vs[0]),
})
}
for k, vs := range r.PostForm {
if k == sessionId || k == apiToken {
continue
}
switch k {
case hob:
hobCode = vs[0]
continue
case city:
if len(vs[0]) == 3 && len(hobCode) != 3 {
hobCode = vs[0]
}
}
// pick first v
protoReq.Post = append(protoReq.Post, &api.Request_Pair{
Key: proto.String(k),
Value: proto.String(vs[0]),
})
}
// need to add HOB back in
if len(hobCode) == 3 {
protoReq.Get = append(protoReq.Get, &api.Request_Pair{
Key: proto.String(hob),
Value: proto.String(hobCode),
})
protoReq.Post = append(protoReq.Post, &api.Request_Pair{
Key: proto.String(hob),
Value: proto.String(hobCode),
})
}
for k, v := range r.Header {
if passHeaders[k] || strings.HasPrefix(k, "X-") { // only pass through custom headers
vals := strings.Join(v, ",")
protoReq.Header = append(protoReq.Header, fmt.Sprintf("%s: %s", k, vals))
}
}
instrumentHob(r, hobCode)
return protoReq, nil
}