forked from go-graphite/carbonapi
-
Notifications
You must be signed in to change notification settings - Fork 1
/
http_common.go
127 lines (105 loc) · 2.54 KB
/
http_common.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type Response struct {
ReplyDelayMS int `yaml:"replyDelayMS"`
PathExpression string `yaml:"pathExpression"`
Data []Metric `yaml:"data"`
}
type Metric struct {
MetricName string `yaml:"metricName"`
Step int `yaml:"step"`
StartTime int `yaml:"startTime"`
Values []float64 `yaml:"values"`
}
type metricForJson struct {
MetricName string
Values []string
}
func (m *Metric) MarshalJSON() ([]byte, error) {
m2 := metricForJson{
MetricName: m.MetricName,
Values: make([]string, len(m.Values)),
}
for i, v := range m.Values {
m2.Values[i] = fmt.Sprintf("%v", v)
}
return json.Marshal(m2)
}
type responseFormat int
const (
jsonFormat responseFormat = iota
pickleFormat
protoV2Format
protoV3Format
)
func getFormat(req *http.Request) (responseFormat, error) {
format := req.FormValue("format")
if format == "" {
format = "json"
}
formatCode, ok := knownFormats[format]
if !ok {
return formatCode, fmt.Errorf("unknown format")
}
return formatCode, nil
}
var knownFormats = map[string]responseFormat{
"json": jsonFormat,
"pickle": pickleFormat,
"protobuf": protoV2Format,
"protobuf3": protoV2Format,
"carbonapi_v2_pb": protoV2Format,
"carbonapi_v3_pb": protoV3Format,
}
func (r responseFormat) String() string {
switch r {
case jsonFormat:
return "json"
case pickleFormat:
return "pickle"
case protoV2Format:
return "carbonapi_v2_pb"
default:
return "unknown"
}
}
func copyResponse(src Response) Response {
dst := Response{
PathExpression: src.PathExpression,
ReplyDelayMS: src.ReplyDelayMS,
Data: make([]Metric, len(src.Data)),
}
for i := range src.Data {
dst.Data[i] = Metric{
MetricName: src.Data[i].MetricName,
Values: make([]float64, len(src.Data[i].Values)),
StartTime: src.Data[i].StartTime,
Step: src.Data[i].Step,
}
for j := range src.Data[i].Values {
dst.Data[i].Values[j] = src.Data[i].Values[j]
}
}
return dst
}
func copyMap(src map[string]Response) map[string]Response {
dst := make(map[string]Response)
for k, v := range src {
dst[k] = copyResponse(v)
}
return dst
}
const (
contentTypeJSON = "application/json"
contentTypeProtobuf = "application/x-protobuf"
contentTypeJavaScript = "text/javascript"
contentTypeRaw = "text/plain"
contentTypePickle = "application/pickle"
contentTypePNG = "image/png"
contentTypeCSV = "text/csv"
contentTypeSVG = "image/svg+xml"
)