-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
79 lines (63 loc) · 1.95 KB
/
client.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
package httpcall
import (
"fmt"
"net/http"
"strings"
"github.com/tetratelabs/proxy-wasm-go-sdk/proxywasm"
)
// Callback represents callback function that has response result as arguments
type Callback func(headers http.Header, body []byte, err error)
// Client represents client for httpcall
type Client interface {
Post(cluster_name, host, path string, header http.Header, body []byte, callback Callback) error
}
// New initializes client that meets Client interface
func New(timeoutMillisecond uint32) Client {
return &client{
timeoutMillisecond: timeoutMillisecond,
}
}
type client struct {
timeoutMillisecond uint32
}
// Post makes a POST request
func (c *client) Post(cluster_name, host, path string, header http.Header, body []byte, callback Callback) error {
header.Set(":authority", host)
header.Set(":method", "POST")
header.Set(":path", path)
header.Set("Accept", "application/json")
if err := c.do(cluster_name, header, body, callback); err != nil {
return fmt.Errorf("failed to make a request: %s", err)
}
return nil
}
func (c *client) do(host string, header http.Header, body []byte, callback Callback) error {
cb := func(numHeaders, bodySize, numTrailers int) {
hs, err := proxywasm.GetHttpCallResponseHeaders()
if err != nil {
callback(nil, nil, fmt.Errorf("failed to get response headers: %s", err))
return
}
respHeader := make(http.Header)
for _, v := range hs {
respHeader.Add(strings.TrimLeft(v[0], ":"), v[1])
}
var body []byte
if bodySize > 0 {
body, err = proxywasm.GetHttpCallResponseBody(0, bodySize)
if err != nil {
callback(nil, nil, fmt.Errorf("failed to get response body: %s", err))
return
}
}
callback(respHeader, body, nil)
}
var reqHeaders [][2]string
for k := range header {
reqHeaders = append(reqHeaders, [2]string{k, header.Get(k)})
}
if _, err := proxywasm.DispatchHttpCall(host, reqHeaders, body, nil, c.timeoutMillisecond, cb); err != nil {
return err
}
return nil
}