Set content-type for mixed-in Prometheus results

Signed-off-by: Alex Ellis <alexellis2@gmail.com>
This commit is contained in:
Alex Ellis
2017-10-29 08:59:52 +00:00
parent 85d3e2ba87
commit 8363532751
4 changed files with 109 additions and 6 deletions

View File

@ -18,10 +18,8 @@ func makeClient() http.Client {
}
// AddMetricsHandler wraps a http.HandlerFunc with Prometheus metrics
func AddMetricsHandler(handler http.HandlerFunc, host string, port int) http.HandlerFunc {
client := makeClient()
func AddMetricsHandler(handler http.HandlerFunc, prometheusQuery PrometheusQueryFetcher) http.HandlerFunc {
prometheusQuery := NewPrometheusQuery(host, port, &client)
return func(w http.ResponseWriter, r *http.Request) {
// log.Printf("Calling upstream for function info\n")
@ -30,11 +28,14 @@ func AddMetricsHandler(handler http.HandlerFunc, host string, port int) http.Han
upstreamCall := recorder.Result()
if upstreamCall.Body == nil {
log.Println("Upstream call had empty body.")
return
}
defer upstreamCall.Body.Close()
if recorder.Code != http.StatusOK {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("Error pulling metrics from provider/backend. Status code: %d", recorder.Code)))
return
@ -44,9 +45,11 @@ func AddMetricsHandler(handler http.HandlerFunc, host string, port int) http.Han
var functions []requests.Function
err := json.Unmarshal(upstreamBody, &functions)
if err != nil {
log.Println(err)
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Error parsing metrics from upstream provider/backend."))
return
@ -58,7 +61,7 @@ func AddMetricsHandler(handler http.HandlerFunc, host string, port int) http.Han
results, fetchErr := prometheusQuery.Fetch(expr)
if fetchErr != nil {
log.Printf("Error querying Prometheus API: %s\n", fetchErr.Error())
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(upstreamBody)
return
@ -73,6 +76,7 @@ func AddMetricsHandler(handler http.HandlerFunc, host string, port int) http.Han
}
// log.Printf("Writing bytesOut: %s\n", bytesOut)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(bytesOut)
}