generated from sensu/check-plugin-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
fake_net.go
72 lines (58 loc) · 1.37 KB
/
fake_net.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
package main
import (
"context"
"net"
"net/http"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// The purpose of this code is to bind a prometheus HTTP handler to a net.Listener
// that doesn't actually open any sockets or files. That lets us re-use the prom
// HTTP logic to scrape the metrics without needing any system permissions to
// open ports or files.
var (
netListener = NewFakeListener()
)
func init() {
go http.Serve(netListener, promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{}))
}
type FakeListener struct {
client net.Conn
server net.Conn
}
func (f *FakeListener) Client() *http.Client {
transport := http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
return f.client, nil
},
}
return &http.Client{
Transport: &transport,
}
}
func NewFakeListener() *FakeListener {
client, server := net.Pipe()
return &FakeListener{
client: client,
server: server,
}
}
func (f *FakeListener) Accept() (net.Conn, error) {
return f.server, nil
}
func (f *FakeListener) Close() error {
_ = f.client.Close()
_ = f.server.Close()
return nil
}
func (f *FakeListener) Addr() net.Addr {
return fakeAddr{}
}
type fakeAddr struct {
}
func (fakeAddr) Network() string {
return "tcp"
}
func (fakeAddr) String() string {
return "fake"
}