Use common/expfmt in federation

This commit is contained in:
Fabian Reinartz 2015-08-21 13:16:50 +02:00
parent 11a577fcd0
commit 47aa0d536c

View file

@ -1,18 +1,15 @@
package web
import (
"io"
"net/http"
"bitbucket.org/ww/goautoneg"
"github.com/golang/protobuf/proto"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/text"
"github.com/prometheus/prometheus/promql"
"github.com/prometheus/prometheus/storage/local"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
"github.com/prometheus/common/model"
)
@ -36,8 +33,10 @@ func (fed *Federation) ServeHTTP(w http.ResponseWriter, req *http.Request) {
}
}
enc, contentType := chooseEncoder(req)
w.Header().Set("Content-Type", contentType)
format := expfmt.Negotiate(req.Header)
w.Header().Set("Content-Type", string(format))
enc := expfmt.NewEncoder(w, format)
protMetric := &dto.Metric{
Label: []*dto.LabelPair{},
@ -70,39 +69,10 @@ func (fed *Federation) ServeHTTP(w http.ResponseWriter, req *http.Request) {
protMetric.TimestampMs = (*int64)(&sp.Timestamp)
protMetric.Untyped.Value = (*float64)(&sp.Value)
if _, err := enc(w, protMetricFam); err != nil {
if err := enc.Encode(protMetricFam); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
type encoder func(w io.Writer, p *dto.MetricFamily) (int, error)
func chooseEncoder(req *http.Request) (encoder, string) {
accepts := goautoneg.ParseAccept(req.Header.Get("Accept"))
for _, accept := range accepts {
switch {
case accept.Type == "application" &&
accept.SubType == "vnd.google.protobuf" &&
accept.Params["proto"] == "io.prometheus.client.MetricFamily":
switch accept.Params["encoding"] {
case "delimited":
return text.WriteProtoDelimited, prometheus.DelimitedTelemetryContentType
case "text":
return text.WriteProtoText, prometheus.ProtoTextTelemetryContentType
case "compact-text":
return text.WriteProtoCompactText, prometheus.ProtoCompactTextTelemetryContentType
default:
continue
}
case accept.Type == "text" &&
accept.SubType == "plain" &&
(accept.Params["version"] == "0.0.4" || accept.Params["version"] == ""):
return text.MetricFamilyToText, prometheus.TextTelemetryContentType
default:
continue
}
}
return text.MetricFamilyToText, prometheus.TextTelemetryContentType
}