diff --git a/plugins/inputs/prometheus/prometheus.go b/plugins/inputs/prometheus/prometheus.go index 03c0b381127c6..ebb01b0c2ad04 100644 --- a/plugins/inputs/prometheus/prometheus.go +++ b/plugins/inputs/prometheus/prometheus.go @@ -364,7 +364,7 @@ func (p *Prometheus) gatherURL(u URLAndAddress, acc telegraf.Accumulator) error if p.HTTPHeaders != nil { for key, value := range p.HTTPHeaders { - req.Header.Add(key, value) + req.Header.Set(key, value) } } diff --git a/plugins/inputs/prometheus/prometheus_test.go b/plugins/inputs/prometheus/prometheus_test.go index 0052560569338..905ddbde721d3 100644 --- a/plugins/inputs/prometheus/prometheus_test.go +++ b/plugins/inputs/prometheus/prometheus_test.go @@ -78,6 +78,65 @@ func TestPrometheusGeneratesMetrics(t *testing.T) { require.True(t, acc.TagValue("test_metric", "url") == ts.URL+"/metrics") } +func TestPrometheusCustomHeader(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Println(r.Header.Get("accept")) + switch r.Header.Get("accept") { + case "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.7,text/plain;version=0.0.4;q=0.3": + _, err := fmt.Fprintln(w, "proto 15 1490802540000") + require.NoError(t, err) + case "text/plain": + _, err := fmt.Fprintln(w, "plain 42 1490802380000") + require.NoError(t, err) + default: + _, err := fmt.Fprintln(w, "other 44 1490802420000") + require.NoError(t, err) + } + })) + defer ts.Close() + + tests := []struct { + name string + headers map[string]string + expectedMeasurementName string + }{ + { + "default", + map[string]string{}, + "proto", + }, + { + "plain text", + map[string]string{ + "accept": "text/plain", + }, + "plain", + }, + { + "other", + map[string]string{ + "accept": "fakeACCEPTitem", + }, + "other", + }, + } + + for _, test := range tests { + p := &Prometheus{ + Log: testutil.Logger{}, + URLs: []string{ts.URL}, + URLTag: "url", + HTTPHeaders: test.headers, + } + err := p.Init() + require.NoError(t, err) + + var acc testutil.Accumulator + require.NoError(t, acc.GatherError(p.Gather)) + require.Equal(t, test.expectedMeasurementName, acc.Metrics[0].Measurement) + } +} + func TestPrometheusGeneratesMetricsWithHostNameTag(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, err := fmt.Fprintln(w, sampleTextFormat)