-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
90 lines (79 loc) · 1.92 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package http
import (
"context"
"fmt"
"net"
"net/http"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/shaardie/connection-exporter/pkg/logging"
)
const (
networkLabel = "network"
urlLabel = "url"
redirectLabel = "redirect"
)
var (
metric = promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "connection_exporter_http_success",
Help: "Successful http request",
}, []string{networkLabel, urlLabel, redirectLabel})
)
type HTTP struct {
cfg Config
client http.Client
metric prometheus.Gauge
}
type Config struct {
URL string
Redirect bool
Network string
}
func New(cfg Config) *HTTP {
dialer := &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}
checkRedirect := func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
if cfg.Redirect {
checkRedirect = nil
}
return &HTTP{
cfg: cfg,
client: http.Client{
CheckRedirect: checkRedirect,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: func(ctx context.Context, _, addr string) (net.Conn, error) {
return dialer.DialContext(ctx, cfg.Network, addr)
},
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
},
metric: metric.With(
prometheus.Labels{
networkLabel: cfg.Network,
urlLabel: cfg.URL,
redirectLabel: fmt.Sprintf("%v", cfg.Redirect),
}),
}
}
func (http *HTTP) Do(ctx context.Context) {
logger := logging.FromContextOrDiscard(ctx)
resp, err := http.client.Get(http.cfg.URL)
if err != nil {
http.metric.Set(0)
logger.Infow("Request failed", "config", http.cfg, "error", err)
return
}
resp.Body.Close()
logger.Infow("Request succeeded", "config", http.cfg)
http.metric.Set(1)
}