-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_stdlib.go
More file actions
88 lines (74 loc) · 1.83 KB
/
client_stdlib.go
File metadata and controls
88 lines (74 loc) · 1.83 KB
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
//go:build !wasm
package fetch
import (
"bytes"
"context"
"io"
"net/http"
"time"
. "github.com/tinywasm/fmt"
)
// doRequest is the standard library implementation for making an HTTP request.
func doRequest(r *Request, callback func(*Response, error)) {
go func() {
// 1. Build the full URL.
fullURL, err := buildURL(r)
if err != nil {
callback(nil, err)
return
}
// 2. Prepare body reader.
var bodyReader io.Reader
if len(r.body) > 0 {
bodyReader = bytes.NewReader(r.body)
}
// 3. Set up the request context with timeout.
ctx := context.Background()
if r.timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, time.Duration(r.timeout)*time.Millisecond)
defer cancel()
}
// 4. Create the HTTP request.
req, err := http.NewRequestWithContext(ctx, r.method, fullURL, bodyReader)
if err != nil {
callback(nil, Errf("failed to create request: %s", err.Error()))
return
}
// 5. Add headers to the request.
for _, h := range r.headers {
req.Header.Add(h.Key, h.Value)
}
// 6. Execute the request.
resp, err := http.DefaultClient.Do(req)
if err != nil {
callback(nil, Errf("request failed: %s", err.Error()))
return
}
defer resp.Body.Close()
// 7. Read the response body.
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
callback(nil, Errf("failed to read response body: %s", err.Error()))
return
}
// 8. Construct the Response object.
var headers []Header
for k, v := range resp.Header {
for _, val := range v {
headers = append(headers, Header{Key: k, Value: val})
}
}
response := &Response{
Status: resp.StatusCode,
Headers: headers,
RequestURL: fullURL,
Method: r.method,
body: responseBody,
}
callback(response, nil)
}()
}
func getOrigin() string {
return ""
}