2015-01-21 11:07:45 -08:00
|
|
|
// Copyright 2013 The Prometheus Authors
|
2013-10-22 11:31:52 -07:00
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
2014-12-10 07:16:49 -08:00
|
|
|
package httputils
|
2013-10-22 11:31:52 -07:00
|
|
|
|
|
|
|
import (
|
2015-03-30 10:43:19 -07:00
|
|
|
"encoding/json"
|
|
|
|
"io"
|
2013-10-22 11:31:52 -07:00
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2015-03-30 10:43:19 -07:00
|
|
|
|
|
|
|
"github.com/prometheus/prometheus/promql"
|
2013-10-22 11:31:52 -07:00
|
|
|
)
|
|
|
|
|
2014-12-10 07:16:49 -08:00
|
|
|
// GetQueryParams calls r.ParseForm and returns r.Form.
|
2013-10-22 11:31:52 -07:00
|
|
|
func GetQueryParams(r *http.Request) url.Values {
|
|
|
|
r.ParseForm()
|
|
|
|
return r.Form
|
|
|
|
}
|
2015-03-30 10:43:19 -07:00
|
|
|
|
|
|
|
var jsonFormatVersion = 1
|
|
|
|
|
|
|
|
// ErrorJSON writes the given error JSON-formatted to w.
|
|
|
|
func ErrorJSON(w io.Writer, err error) error {
|
|
|
|
data := struct {
|
|
|
|
Type string `json:"type"`
|
|
|
|
Value string `json:"value"`
|
|
|
|
Version int `json:"version"`
|
|
|
|
}{
|
|
|
|
Type: "error",
|
|
|
|
Value: err.Error(),
|
|
|
|
Version: jsonFormatVersion,
|
|
|
|
}
|
|
|
|
enc := json.NewEncoder(w)
|
|
|
|
return enc.Encode(data)
|
|
|
|
}
|
|
|
|
|
|
|
|
// RespondJSON converts the given data value to JSON and writes it to w.
|
|
|
|
func RespondJSON(w io.Writer, val promql.Value) error {
|
|
|
|
data := struct {
|
|
|
|
Type string `json:"type"`
|
|
|
|
Value interface{} `json:"value"`
|
|
|
|
Version int `json:"version"`
|
|
|
|
}{
|
|
|
|
Type: val.Type().String(),
|
|
|
|
Value: val,
|
|
|
|
Version: jsonFormatVersion,
|
|
|
|
}
|
|
|
|
// TODO(fabxc): Adding MarshalJSON to promql.Values might be a good idea.
|
|
|
|
if sc, ok := val.(*promql.Scalar); ok {
|
|
|
|
data.Value = sc.Value
|
|
|
|
}
|
|
|
|
enc := json.NewEncoder(w)
|
|
|
|
return enc.Encode(data)
|
|
|
|
}
|