-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathhttp.go
68 lines (61 loc) · 1.88 KB
/
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
package rpc
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
)
// createRequest
func (p *Provider) createRequest(ctx context.Context, rp RequestPayload) (*http.Request, error) {
var data []byte
if rj := p.Opts.Experimental.CustomRequestPayload; rj != nil && p.Opts.Experimental.DotPath != "" {
d, err := rp.embedPayload(rj, p.Opts.Experimental.DotPath)
if err != nil {
return nil, err
}
data = d
} else {
d, err := json.Marshal(rp)
if err != nil {
return nil, err
}
data = d
}
req, err := http.NewRequestWithContext(ctx, p.Opts.Request.HTTPMethod, p.listenerURL.String(), bytes.NewReader(data))
if err != nil {
return nil, err
}
for k, v := range p.Opts.Request.StaticHeaders {
req.Header.Add(k, strings.Join(v, ","))
}
if p.Opts.Request.HTTPContentType != "" {
req.Header.Set("Content-Type", p.Opts.Request.HTTPContentType)
}
if p.Opts.Request.TimestampHeader != "" {
req.Header.Add(p.Opts.Request.TimestampHeader, time.Now().Format(p.Opts.Request.TimestampFormat))
}
return req, nil
}
func (p *Provider) handleResponse(statusCode int, headers http.Header, body *bytes.Buffer, reqKeysAndValues []any) (ResponsePayload, error) {
kvs := reqKeysAndValues
defer func() {
if !p.LogNotificationsDisabled {
kvs = append(kvs, responseKVS(statusCode, headers, body)...)
p.Logger.Info("rpc notification details", kvs...)
}
}()
res := ResponsePayload{}
if err := json.Unmarshal(body.Bytes(), &res); err != nil {
if statusCode != http.StatusOK {
return ResponsePayload{}, fmt.Errorf("unexpected status code: %d, response error(optional): %v", statusCode, res.Error)
}
return ResponsePayload{}, fmt.Errorf("failed to parse response: %w", err)
}
if statusCode != http.StatusOK {
return ResponsePayload{}, fmt.Errorf("unexpected status code: %d, response error(optional): %v", statusCode, res.Error)
}
return res, nil
}