forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
75 lines (69 loc) · 1.43 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
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package tests
import (
"bufio"
"context"
"fmt"
"io"
"net/http"
"strconv"
"strings"
)
func GetMetricsValue(url string, metrics ...string) (map[string]float64, error) {
lines, err := getHTTPLines(url)
if err != nil {
return nil, err
}
mm := make(map[string]float64, len(metrics))
for _, line := range lines {
if strings.HasPrefix(line, "# ") {
continue
}
found, name := false, ""
for _, name = range metrics {
if !strings.HasPrefix(line, name) {
continue
}
found = true
break
}
if !found || name == "" { // no matched metric found
continue
}
ll := strings.Split(line, " ")
if len(ll) != 2 {
continue
}
fv, err := strconv.ParseFloat(ll[1], 64)
if err != nil {
return nil, fmt.Errorf("failed to parse %q (%w)", ll, err)
}
mm[name] = fv
}
return mm, nil
}
func getHTTPLines(url string) ([]string, error) {
req, err := http.NewRequestWithContext(context.TODO(), "GET", url, nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
rd := bufio.NewReader(resp.Body)
lines := []string{}
for {
line, err := rd.ReadString('\n')
if err != nil {
if err == io.EOF {
break
}
_ = resp.Body.Close()
return nil, err
}
lines = append(lines, strings.TrimSpace(line))
}
return lines, resp.Body.Close()
}