Skip to content

Commit

Permalink
fix(inputs.prometheus): Use set over add for custom headers (influxda…
Browse files Browse the repository at this point in the history
  • Loading branch information
powersj authored Mar 21, 2023
1 parent 08ccdde commit 77bebd8
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
2 changes: 1 addition & 1 deletion plugins/inputs/prometheus/prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down
59 changes: 59 additions & 0 deletions plugins/inputs/prometheus/prometheus_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 77bebd8

Please sign in to comment.