-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhostfunc.http.go
217 lines (178 loc) · 6.07 KB
/
hostfunc.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
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package capsule
import (
"context"
"encoding/json"
"errors"
//"fmt"
"log"
"strconv"
"github.com/go-resty/resty/v2"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/api"
)
//! THIS IS A WORK IN PROGRESS → it does not work very well with big requests
// request embeds the data of the http request
type request struct {
JSONBody map[string]interface{} `json:"JSONBody"`
TextBody string `json:"TextBody"`
//Body string `json:"Body"`
URI string `json:"URI"`
Method string `json:"Method"`
Headers map[string]string `json:"Headers"`
}
// DefineHostFuncHTTP defines the host module function for handling HTTP requests.
//
// Parameter(s):
// builder: the wazero.HostModuleBuilder used to define the function.
//
// Return(s):
// None.
func DefineHostFuncHTTP(builder wazero.HostModuleBuilder) {
builder.NewFunctionBuilder().
WithGoModuleFunction(http,
[]api.ValueType{
api.ValueTypeI32, // request position
api.ValueTypeI32, // request length
api.ValueTypeI32, // returned value position
api.ValueTypeI32, // returned value length
},
[]api.ValueType{api.ValueTypeI32}).
Export("hostHTTP")
}
// http : host function called by the wasm function
// and then returning data to the wasm module
var http = api.GoModuleFunc(func(ctx context.Context, module api.Module, params []uint64) {
requestPosition := uint32(params[0])
requestLength := uint32(params[1])
bufferRequest, err := ReadBytesParameterFromMemory(module, requestPosition, requestLength)
if err != nil {
log.Panicf("❌ Error (bufferRequest): ReadBytesParameterFromMemory(%d, %d) out of range", requestPosition, requestLength)
}
// unmarshal the request
var req request
errMarshal := json.Unmarshal(bufferRequest, &req)
if errMarshal != nil {
log.Println("❌ Error when unmarshal the request", errMarshal)
}
var resultFromHost []byte
httpClient := resty.New()
for key, value := range req.Headers {
httpClient.SetHeader(key, value)
}
switch what := req.Method; what {
case "GET":
resp, err := httpClient.R().EnableTrace().Get(req.URI)
if err != nil {
resultFromHost = failure([]byte(err.Error()))
} else {
jsonHTTPResponse, err := buildResponseJSONString(resp)
if err != nil {
resultFromHost = failure([]byte(err.Error()))
}
resultFromHost = success([]byte(jsonHTTPResponse))
}
case "POST":
var body string
/*
if req.Body != "" { // TODO: remove Body
body = req.Body
} else if req.JSONBody != nil {
buff, _ := json.Marshal(req.JSONBody)
// TODO: handle error
body = string(buff)
} else if req.TextBody != "" {
body = req.TextBody
}
*/
if req.JSONBody != nil {
buff, _ := json.Marshal(req.JSONBody)
// TODO: handle error
body = string(buff)
} else if req.TextBody != "" {
body = req.TextBody
}
resp, err := httpClient.R().EnableTrace().SetBody(body).Post(req.URI)
if err != nil {
resultFromHost = failure([]byte(err.Error()))
} else {
jsonHTTPResponse, err := buildResponseJSONString(resp)
if err != nil {
resultFromHost = failure([]byte(err.Error()))
}
resultFromHost = success([]byte(jsonHTTPResponse))
}
case "PUT":
// TODO: test it
var body string
if req.JSONBody != nil {
buff, _ := json.Marshal(req.JSONBody)
// TODO: handle error
body = string(buff)
} else if req.TextBody != "" {
body = req.TextBody
}
resp, err := httpClient.R().EnableTrace().SetBody(body).Put(req.URI)
if err != nil {
resultFromHost = failure([]byte(err.Error()))
} else {
jsonHTTPResponse, err := buildResponseJSONString(resp)
if err != nil {
resultFromHost = failure([]byte(err.Error()))
}
resultFromHost = success([]byte(jsonHTTPResponse))
}
case "DELETE":
// TODO: test it
resp, err := httpClient.R().EnableTrace().Delete(req.URI)
if err != nil {
resultFromHost = failure([]byte(err.Error()))
} else {
jsonHTTPResponse, err := buildResponseJSONString(resp)
if err != nil {
resultFromHost = failure([]byte(err.Error()))
}
resultFromHost = success([]byte(jsonHTTPResponse))
}
default:
resultFromHost = failure([]byte(errors.New("❌ Error: " + req.Method + " is not yet implemented").Error()))
}
positionReturnBuffer := uint32(params[2])
lengthReturnBuffer := uint32(params[3])
_, errReturn := ReturnBytesToMemory(ctx, module, positionReturnBuffer, lengthReturnBuffer, resultFromHost)
if errReturn != nil {
log.Panicf("❌ Error: ReturnBytesToMemory(%d, %d) out of range", positionReturnBuffer, lengthReturnBuffer)
}
params[0] = 0
})
// buildResponseJSONString takes a resty.Response pointer as input and returns a JSON string and an error.
// The function builds a JSON string of the response headers and response body. If the response is in JSON format,
// the function includes the JSON body in the JSON string; otherwise, the function includes the text body in the JSON
// string with double quotes. The function also includes the status code in the JSON string.
func buildResponseJSONString(resp *resty.Response) (string, error) {
// build headers JSON string
// ! ATTENTION resp.Header() return a map[string]string[] (instead of map[string]string)
// TODO: on the guest side, add method to the structure to read the headers
// TODO: rebuild the headers and copy it to a map[string]string
/*
for key, value := range resp.Header() {
fmt.Println(key, value[0])
}
*/
// TODO: or try with another library
jsonHeaders, err := json.Marshal(resp.Header())
responseBody := resp.String() //? marshall or not?
statusCode := resp.StatusCode()
isJSON := false
contentType, ok := resp.Header()["Content-Type"]
if ok {
isJSON = resty.IsJSONType(contentType[0])
}
var jsonHTTPResponse string
if isJSON {
jsonHTTPResponse = `{"JSONBody":` + responseBody + `,"Headers":` + string(jsonHeaders) + `,"StatusCode":` + strconv.Itoa(statusCode) + `}`
} else {
// add double quotes for body
jsonHTTPResponse = `{"TextBody":"` + responseBody + `","Headers":` + string(jsonHeaders) + `,"StatusCode":` + strconv.Itoa(statusCode) + `}`
}
return jsonHTTPResponse, err
}