Skip to content

Commit 74f642c

Browse files
committed
added a module to refactor the method
1 parent 5db147f commit 74f642c

File tree

2 files changed

+20
-11
lines changed

2 files changed

+20
-11
lines changed

pkg/services/alertmanager.go

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -211,18 +211,10 @@ func (s alertmanagerService) Send(notification Notification, dest Destination) e
211211
func (s alertmanagerService) sendOneTarget(ctx context.Context, target string, rawBody []byte) (err error) {
212212
rawURL := fmt.Sprintf("%v://%v%v", s.opts.Scheme, target, s.opts.APIPath)
213213

214-
var idleConnTimeout time.Duration
215-
if s.opts.IdleConnTimeout != "" {
216-
idleConnTimeout, err = time.ParseDuration(s.opts.IdleConnTimeout)
217-
if err != nil {
218-
return fmt.Errorf("failed to parse idle connection timeout: %w", err)
219-
}
220-
}
221-
transport := httputil.NewTransport(rawURL, s.opts.MaxIdleConns, s.opts.MaxIdleConnsPerHost, s.opts.MaxConnsPerHost, idleConnTimeout, s.opts.InsecureSkipVerify)
222-
client := &http.Client{
223-
Transport: httputil.NewLoggingRoundTripper(transport, s.entry),
214+
client, err := httputil.NewServiceHTTPClient(s.opts.MaxIdleConns, s.opts.MaxIdleConnsPerHost, s.opts.MaxConnsPerHost, s.opts.IdleConnTimeout, s.opts.InsecureSkipVerify, rawURL, "alertmeanger")
215+
if err != nil {
216+
return err
224217
}
225-
226218
req, err := http.NewRequestWithContext(ctx, http.MethodPost, rawURL, bytes.NewReader(rawBody))
227219
if err != nil {
228220
return err

pkg/util/http/transport.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,12 @@ package http
33
import (
44
"crypto/tls"
55
"crypto/x509"
6+
"fmt"
67
"net/http"
78
"net/url"
89
"time"
10+
11+
log "github.com/sirupsen/logrus"
912
)
1013

1114
var certResolver func(serverName string) ([]string, error)
@@ -43,6 +46,20 @@ func NewTransport(rawURL string, maxIdleConns int, maxIdleConnsPerHost int, maxC
4346
return transport
4447
}
4548

49+
func NewServiceHTTPClient(maxIdleConns, maxIdleConnsPerHost, maxConnsPerHost int, idleConnTimeout string, insecureSkipVerify bool, apiURL string, serviceName string) (client *http.Client, err error) {
50+
var timeout time.Duration
51+
if idleConnTimeout != "" {
52+
timeout, err = time.ParseDuration(idleConnTimeout)
53+
if err != nil {
54+
return nil, fmt.Errorf("failed to parse idle connection timeout: %w", err)
55+
}
56+
}
57+
transport := NewTransport(apiURL, maxIdleConns, maxIdleConnsPerHost, maxConnsPerHost, timeout, insecureSkipVerify)
58+
return &http.Client{
59+
Transport: NewLoggingRoundTripper(transport, log.WithField("service", serviceName)),
60+
}, nil
61+
}
62+
4663
func getCertPoolFromPEMData(pemData []string) *x509.CertPool {
4764
certPool := x509.NewCertPool()
4865
for _, pem := range pemData {

0 commit comments

Comments
 (0)