-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathtranslate.go
201 lines (173 loc) · 5.49 KB
/
translate.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
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package crosscoap
import (
"bytes"
"net/http"
"net/url"
"strings"
"github.com/dustin/go-coap"
)
const maxCOAPPacketLen = 1500
type translatedCOAPMessage struct {
coap.Message
IsTruncated bool
}
type content struct {
Type string
Encoding string
}
const appJSONDeflate coap.MediaType = 11050
var coapContentFormatContentType = map[coap.MediaType]content{
coap.TextPlain: content{Type: "text/plain;charset=utf-8"},
coap.AppLinkFormat: content{Type: "application/link-format"},
coap.AppXML: content{Type: "application/xml"},
coap.AppOctets: content{Type: "application/octet-stream"},
coap.AppExi: content{Type: "application/exi"},
coap.AppJSON: content{Type: "application/json"},
appJSONDeflate: content{Type: "application/json", Encoding: "deflate"},
}
var httpStatusCOAPCode = map[int]coap.COAPCode{
http.StatusOK: coap.Content,
http.StatusCreated: coap.Created,
http.StatusNoContent: coap.Content,
http.StatusNotModified: coap.Valid,
http.StatusBadRequest: coap.BadRequest,
http.StatusUnauthorized: coap.Unauthorized,
http.StatusForbidden: coap.Forbidden,
http.StatusNotFound: coap.NotFound,
http.StatusMethodNotAllowed: coap.MethodNotAllowed,
http.StatusNotAcceptable: coap.NotAcceptable,
http.StatusPreconditionFailed: coap.PreconditionFailed,
http.StatusRequestEntityTooLarge: coap.RequestEntityTooLarge,
http.StatusUnsupportedMediaType: coap.UnsupportedMediaType,
http.StatusInternalServerError: coap.InternalServerError,
http.StatusNotImplemented: coap.NotImplemented,
http.StatusBadGateway: coap.BadGateway,
http.StatusServiceUnavailable: coap.ServiceUnavailable,
http.StatusGatewayTimeout: coap.GatewayTimeout,
}
func translateStatusCode(httpStatusCode int) coap.COAPCode {
coapCode, found := httpStatusCOAPCode[httpStatusCode]
if found {
return coapCode
}
return coap.Content
}
func trimCharset(val string) string {
return strings.SplitN(val, ";", 2)[0]
}
func translateContentTypeWithEncoding(contentType, contentEncoding string) (coap.MediaType, bool) {
contentType = trimCharset(contentType)
for mediaType, ct := range coapContentFormatContentType {
if trimCharset(ct.Type) == contentType && ct.Encoding == contentEncoding {
return mediaType, true
}
}
return 0, false
}
func getContentFormatFromCoapMessage(msg coap.Message) (content, bool) {
contentFormat := msg.Option(coap.ContentFormat)
if contentFormat != nil {
ct, found := coapContentFormatContentType[contentFormat.(coap.MediaType)]
return ct, found
}
return content{}, false
}
func escapeKeyValue(s string) string {
kv := strings.SplitN(s, "=", 2)
if len(kv) == 1 {
return url.QueryEscape(kv[0])
}
return url.QueryEscape(kv[0]) + "=" + url.QueryEscape(kv[1])
}
func queryString(coapMsg *coap.Message) string {
uriQueryOptions := coapMsg.Options(coap.URIQuery)
parts := make([]string, 0, len(uriQueryOptions))
for _, part := range uriQueryOptions {
partStr, ok := part.(string)
if !ok {
continue
}
parts = append(parts, escapeKeyValue(partStr))
}
if len(parts) == 0 {
return ""
}
return "?" + strings.Join(parts, "&")
}
func translateCOAPRequestToHTTPRequest(coapMsg *coap.Message, backendURLPrefix string) *http.Request {
method := coapMsg.Code.String()
url := addFinalSlash(backendURLPrefix) + coapMsg.PathString() + queryString(coapMsg)
body := bytes.NewReader(coapMsg.Payload)
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil
}
if s, ok := coapMsg.Option(coap.URIHost).(string); ok {
req.Host = s
}
contentFormat, found := getContentFormatFromCoapMessage(*coapMsg)
if found {
if contentFormat.Type != "" {
req.Header.Set("Content-Type", contentFormat.Type)
}
if contentFormat.Encoding != "" {
req.Header.Set("Content-Encoding", contentFormat.Encoding)
}
}
return req
}
func translateHTTPResponseToCOAPResponse(httpResp *http.Response, httpBody []byte, httpError error, coapRequest *coap.Message) (*translatedCOAPMessage, error) {
coapResp := translatedCOAPMessage{
Message: coap.Message{
Type: coap.Acknowledgement,
MessageID: coapRequest.MessageID,
Token: coapRequest.Token,
},
IsTruncated: false,
}
if httpError != nil {
coapResp.Code = coap.ServiceUnavailable
return &coapResp, nil
}
coapResp.Code = translateStatusCode(httpResp.StatusCode)
contentFormat, hasContentFormat := translateContentTypeWithEncoding(
httpResp.Header.Get("Content-Type"),
httpResp.Header.Get("Content-Encoding"))
if hasContentFormat {
coapResp.SetOption(coap.ContentFormat, contentFormat)
}
// intermediate marshalling
packetHeaders, err := coapResp.MarshalBinary()
if err != nil {
coapResp.Code = coap.InternalServerError
coapResp.RemoveOption(coap.ContentFormat)
return &coapResp, err
}
// Check the size so far (+ 1 byte for the payload separator 0xff)
headersLen := len(packetHeaders) + 1
bytesLeft := maxCOAPPacketLen - headersLen
if len(httpBody) > bytesLeft {
coapResp.Payload = httpBody[:bytesLeft]
coapResp.IsTruncated = true
} else {
coapResp.Payload = httpBody
}
return &coapResp, nil
}
func generateBadRequestCOAPResponse(coapRequest *coap.Message) *translatedCOAPMessage {
return &translatedCOAPMessage{
Message: coap.Message{
Type: coap.Acknowledgement,
Code: coap.BadRequest,
MessageID: coapRequest.MessageID,
Token: coapRequest.Token,
},
IsTruncated: false,
}
}
func addFinalSlash(s string) string {
if strings.HasSuffix(s, "/") {
return s
}
return s + "/"
}