-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtmp_httpclient_example.go
105 lines (86 loc) · 2.14 KB
/
tmp_httpclient_example.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
package httpclient
import (
"context"
"fmt"
"net/http"
"time"
"go.uber.org/zap"
{{range .imports}}
"{{.}}"
{{- end}}
)
type (
// ExampleClient is a http client
ExampleClient struct {
*http.Client
log *logging.Logger
config *config
}
examplePayload struct {
EventType string `json:"eventType"`
Payload map[string]interface{} `json:"payload"`
}
)
const (
defaultTimeout = 30 * time.Second
)
// NewExampleClient creates a new ExampleClient.
func NewExampleClient(instrumentation *telemetry.Instrumentation) *ExampleClient {
name := "example.client"
logger := logging.NewLogger()
cfg := newConfig()
return &ExampleClient{
Client: newHTTPClient(
useOTELRoundTripper(),
useMetricsRoundTripper(name, instrumentation.Registry()),
useLoggerRoundTripper(name, logger),
),
config: cfg,
log: logger,
}
}
// ExternalRequest sends a request to an external service.
func (client *ExampleClient) ExternalRequest(ctx context.Context) error {
payload := examplePayload{
Payload: map[string]interface{}{
"key": "value",
},
}
token := "Bearer " + client.config.ExampleAPIKey
headers := map[string]string{
"Content-Type": jsonContentType,
"Authorization": token,
}
client.log.Debug(
"make http request to create message",
zap.Any("payload", payload),
zap.Any("headers", headers),
)
req := &httpRequest{
host: client.config.ExampleHost + "/api/v1",
payload: payload,
headers: headers,
method: http.MethodPost,
}
client.log.Debug("sending http request to external service")
response, err := req.make(ctx, client.Client)
if err != nil {
client.log.Error(
"http request to create message failed",
zap.Error(err),
zap.String("responseBody", string(response.Body)),
zap.Int("responseStatusCode", response.StatusCode),
)
return err
}
client.log.Debug(
"http response from external service",
zap.String("responseBody", string(response.Body)),
zap.Int("responseStatusCode", response.StatusCode),
)
if response.StatusCode >= http.StatusIMUsed {
return fmt.Errorf("unexpected status code: %d", response.StatusCode)
}
client.log.Debug("success")
return nil
}