-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
utils.go
111 lines (95 loc) · 2.29 KB
/
utils.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
106
107
108
109
110
111
package main
import (
"fmt"
"net/http"
"sort"
"strings"
"time"
"github.com/VictoriaMetrics/VictoriaMetrics/lib/prompbmarshal"
)
func newTimeSeries(values []float64, timestamps []int64, labels map[string]string) prompbmarshal.TimeSeries {
ts := prompbmarshal.TimeSeries{
Samples: make([]prompbmarshal.Sample, len(values)),
}
for i := range values {
ts.Samples[i] = prompbmarshal.Sample{
Value: values[i],
Timestamp: time.Unix(timestamps[i], 0).UnixNano() / 1e6,
}
}
keys := make([]string, 0, len(labels))
for k := range labels {
keys = append(keys, k)
}
sort.Strings(keys) // make order deterministic
for _, key := range keys {
ts.Labels = append(ts.Labels, prompbmarshal.Label{
Name: key,
Value: labels[key],
})
}
return ts
}
// newTimeSeriesPB creates prompbmarshal.TimeSeries with given
// values, timestamps and labels.
// It expects that labels are already sorted.
func newTimeSeriesPB(values []float64, timestamps []int64, labels []prompbmarshal.Label) prompbmarshal.TimeSeries {
ts := prompbmarshal.TimeSeries{
Samples: make([]prompbmarshal.Sample, len(values)),
}
for i := range values {
ts.Samples[i] = prompbmarshal.Sample{
Value: values[i],
Timestamp: time.Unix(timestamps[i], 0).UnixNano() / 1e6,
}
}
ts.Labels = labels
return ts
}
type curlWriter struct {
b strings.Builder
}
func (cw *curlWriter) string() string {
res := "curl " + cw.b.String()
cw.b.Reset()
return strings.TrimSpace(res)
}
func (cw *curlWriter) addWithEsc(str string) {
escStr := `'` + strings.Replace(str, `'`, `'\''`, -1) + `'`
cw.add(escStr)
}
func (cw *curlWriter) add(str string) {
cw.b.WriteString(str)
cw.b.WriteString(" ")
}
func requestToCurl(req *http.Request) string {
if req.URL == nil {
return ""
}
cw := &curlWriter{}
schema := req.URL.Scheme
requestURL := req.URL.String()
if schema == "" {
schema = "http"
if req.TLS != nil {
schema = "https"
}
requestURL = schema + "://" + req.Host + requestURL
}
if schema == "https" {
cw.add("-k")
}
cw.add("-X")
cw.add(req.Method)
var keys []string
for k := range req.Header {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
cw.add("-H")
cw.addWithEsc(fmt.Sprintf("%s: %s", k, strings.Join(req.Header[k], " ")))
}
cw.addWithEsc(requestURL)
return cw.string()
}