github.com/go-graphite/carbonapi@v0.17.0/cmd/mockbackend/http_common.go (about) 1 package main 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "net/http" 7 ) 8 9 type Response struct { 10 Code int `yaml:"code"` 11 ReplyDelayMS int `yaml:"replyDelayMS"` 12 PathExpression string `yaml:"pathExpression"` 13 Data []Metric `yaml:"data"` 14 Tags []string `yaml:"tags"` 15 } 16 17 type Metric struct { 18 MetricName string `yaml:"metricName"` 19 Step int `yaml:"step"` 20 StartTime int `yaml:"startTime"` 21 Values []float64 `yaml:"values"` 22 } 23 24 type metricForJson struct { 25 MetricName string 26 Values []string 27 } 28 29 func (m *Metric) MarshalJSON() ([]byte, error) { 30 m2 := metricForJson{ 31 MetricName: m.MetricName, 32 Values: make([]string, len(m.Values)), 33 } 34 35 for i, v := range m.Values { 36 m2.Values[i] = fmt.Sprintf("%v", v) 37 } 38 39 return json.Marshal(m2) 40 } 41 42 type responseFormat int 43 44 const ( 45 jsonFormat responseFormat = iota 46 pickleFormat 47 protoV2Format 48 protoV3Format 49 ) 50 51 func getFormat(req *http.Request) (responseFormat, error) { 52 format := req.FormValue("format") 53 if format == "" { 54 format = "json" 55 } 56 57 formatCode, ok := knownFormats[format] 58 if !ok { 59 return formatCode, fmt.Errorf("unknown format") 60 } 61 62 return formatCode, nil 63 } 64 65 var knownFormats = map[string]responseFormat{ 66 "json": jsonFormat, 67 "pickle": pickleFormat, 68 "protobuf": protoV2Format, 69 "protobuf3": protoV2Format, 70 "carbonapi_v2_pb": protoV2Format, 71 "carbonapi_v3_pb": protoV3Format, 72 } 73 74 func (r responseFormat) String() string { 75 switch r { 76 case jsonFormat: 77 return "json" 78 case pickleFormat: 79 return "pickle" 80 case protoV2Format: 81 return "carbonapi_v2_pb" 82 default: 83 return "unknown" 84 } 85 } 86 87 func copyResponse(src Response) Response { 88 dst := Response{ 89 PathExpression: src.PathExpression, 90 ReplyDelayMS: src.ReplyDelayMS, 91 Data: make([]Metric, len(src.Data)), 92 } 93 94 for i := range src.Data { 95 dst.Data[i] = Metric{ 96 MetricName: src.Data[i].MetricName, 97 Values: make([]float64, len(src.Data[i].Values)), 98 StartTime: src.Data[i].StartTime, 99 Step: src.Data[i].Step, 100 } 101 102 copy(dst.Data[i].Values, src.Data[i].Values) 103 } 104 105 return dst 106 } 107 108 func copyMap(src map[string]Response) map[string]Response { 109 dst := make(map[string]Response) 110 111 for k, v := range src { 112 dst[k] = copyResponse(v) 113 } 114 115 return dst 116 } 117 118 const ( 119 contentTypeJSON = "application/json" 120 contentTypeProtobuf = "application/x-protobuf" 121 contentTypeJavaScript = "text/javascript" 122 contentTypeRaw = "text/plain" 123 contentTypePickle = "application/pickle" 124 contentTypePNG = "image/png" 125 contentTypeCSV = "text/csv" 126 contentTypeSVG = "image/svg+xml" 127 )