Skip to content

Commit

Permalink
fix: use readers over closers in http input (#11083)
Browse files Browse the repository at this point in the history
  • Loading branch information
powersj authored May 18, 2022
1 parent 6b697db commit dad330c
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 6 deletions.
15 changes: 9 additions & 6 deletions plugins/inputs/http/http.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package http

import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
Expand Down Expand Up @@ -95,9 +97,6 @@ func (h *HTTP) gatherURL(
if err != nil {
return err
}
if body != nil {
defer body.Close()
}

request, err := http.NewRequest(h.Method, url, body)
if err != nil {
Expand Down Expand Up @@ -175,7 +174,7 @@ func (h *HTTP) gatherURL(
return nil
}

func makeRequestBodyReader(contentEncoding, body string) (io.ReadCloser, error) {
func makeRequestBodyReader(contentEncoding, body string) (io.Reader, error) {
if body == "" {
return nil, nil
}
Expand All @@ -186,10 +185,14 @@ func makeRequestBodyReader(contentEncoding, body string) (io.ReadCloser, error)
if err != nil {
return nil, err
}
return rc, nil
data, err := ioutil.ReadAll(rc)
if err != nil {
return nil, err
}
return bytes.NewReader(data), nil
}

return io.NopCloser(reader), nil
return reader, nil
}

func init() {
Expand Down
34 changes: 34 additions & 0 deletions plugins/inputs/http/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,40 @@ func TestHTTPHeaders(t *testing.T) {
require.NoError(t, acc.GatherError(plugin.Gather))
}

func TestHTTPContentLengthHeader(t *testing.T) {
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/endpoint" {
if r.Header.Get("Content-Length") != "" {
_, _ = w.Write([]byte(simpleJSON))
} else {
w.WriteHeader(http.StatusForbidden)
}
} else {
w.WriteHeader(http.StatusNotFound)
}
}))
defer fakeServer.Close()

address := fakeServer.URL + "/endpoint"
plugin := &httpplugin.HTTP{
URLs: []string{address},
Headers: map[string]string{},
Body: "{}",
Log: testutil.Logger{},
}

plugin.SetParserFunc(func() (telegraf.Parser, error) {
return parsers.NewParser(&parsers.Config{
DataFormat: "json",
MetricName: "metricName",
})
})

var acc testutil.Accumulator
require.NoError(t, plugin.Init())
require.NoError(t, acc.GatherError(plugin.Gather))
}

func TestInvalidStatusCode(t *testing.T) {
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
Expand Down

0 comments on commit dad330c

Please sign in to comment.