-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandle.http.go
89 lines (70 loc) · 2.42 KB
/
handle.http.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
package capsule
import (
"encoding/base64"
"strconv"
"github.com/valyala/fastjson"
)
var handleHTTPFunction func(param HTTPRequest) (HTTPResponse, error)
// SetHandleHTTP sets the handle function
func SetHandleHTTP(function func(param HTTPRequest) (HTTPResponse, error)) {
handleHTTPFunction = function
}
// StringifyHTTPResponse converts a HTTPResponse to a string
func StringifyHTTPResponse(response HTTPResponse) string {
var jsonBody string
if len(response.JSONBody) == 0 {
jsonBody = "{}"
} else {
jsonBody = response.JSONBody
}
var textBody string
if len(response.TextBody) == 0 {
textBody = ""
} else {
// avoid special characters in jsonString
textBody = base64.StdEncoding.EncodeToString([]byte(response.TextBody))
//textBody = retValue.TextBody
}
jsonHTTPResponse := `{"JSONBody":` + jsonBody + `,"TextBody":"` + textBody + `","Headers":` + response.Headers + `,"StatusCode":` + strconv.Itoa(response.StatusCode) + `}`
return jsonHTTPResponse
}
//export callHandleHTTP
func callHandleHTTP(JSONDataPos *uint32, JSONDataSize uint32) uint64 {
parser := fastjson.Parser{}
JSONDataBuffer := readBufferFromMemory(JSONDataPos, JSONDataSize)
JSONData, err := parser.ParseBytes(JSONDataBuffer)
if err != nil {
return failure([]byte(err.Error()))
}
httpRequestParam := HTTPRequest{
Body: string(JSONData.GetStringBytes("Body")),
//JSONBody: string(JSONData.GetStringBytes("JSONBody")), //! to use in the future
//TextBody: string(JSONData.GetStringBytes("TextBody")), //! to use in the future
URI: string(JSONData.GetStringBytes("URI")),
Method: string(JSONData.GetStringBytes("Method")),
Headers: string(JSONData.GetStringBytes("Headers")),
}
// call the handle function
retValue, err := handleHTTPFunction(httpRequestParam)
// return failure or success
if err != nil {
return failure([]byte(err.Error()))
}
var jsonBody string
if len(retValue.JSONBody) == 0 {
jsonBody = "{}"
} else {
jsonBody = retValue.JSONBody
}
var textBody string
if len(retValue.TextBody) == 0 {
textBody = ""
} else {
// avoid special characters in jsonString
textBody = base64.StdEncoding.EncodeToString([]byte(retValue.TextBody))
//textBody = retValue.TextBody
}
jsonHTTPResponse := `{"JSONBody":` + jsonBody + `,"TextBody":"` + textBody + `","Headers":` + retValue.Headers + `,"StatusCode":` + strconv.Itoa(retValue.StatusCode) + `}`
// first byte == 82
return success([]byte(jsonHTTPResponse))
}