-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
request.go
111 lines (89 loc) · 1.8 KB
/
request.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
package wasmhttp
import (
"io"
"net/http"
"net/http/httptest"
"syscall/js"
promise "github.com/nlepage/go-js-promise"
"github.com/nlepage/go-wasm-http-server/v2/internal/readablestream"
"github.com/nlepage/go-wasm-http-server/v2/internal/safejs"
)
// Request builds and returns the equivalent http.Request
func Request(uvalue js.Value) (*http.Request, error) {
value := safejs.Safe(uvalue)
method, err := value.GetString("method")
if err != nil {
return nil, err
}
url, err := value.GetString("url")
if err != nil {
return nil, err
}
body, err := value.Get("body")
if err != nil {
return nil, err
}
var bodyReader io.Reader
if !body.IsNull() {
// WORKAROUND: Firefox does not have request.body ReadableStream
if body.IsUndefined() {
blobp, err := value.Call("blob")
if err != nil {
return nil, err
}
blob, err := promise.Await(safejs.Unsafe(blobp))
if err != nil {
return nil, err
}
body, err = safejs.Safe(blob).Call("stream")
if err != nil {
return nil, err
}
}
r, err := body.Call("getReader")
if err != nil {
return nil, err
}
bodyReader = readablestream.NewReader(r)
}
req := httptest.NewRequest(
method,
url,
bodyReader,
)
headers, err := value.Get("headers")
if err != nil {
return nil, err
}
headersIt, err := headers.Call("entries")
if err != nil {
return nil, err
}
for {
e, err := headersIt.Call("next")
if err != nil {
return nil, err
}
done, err := e.GetBool("done")
if err != nil {
return nil, err
}
if done {
break
}
v, err := e.Get("value")
if err != nil {
return nil, err
}
key, err := v.IndexString(0)
if err != nil {
return nil, err
}
value, err := v.IndexString(1)
if err != nil {
return nil, err
}
req.Header.Set(key, value)
}
return req, nil
}