From 8e7cf0109edc54e7550a10b3713fa3663c888e6f Mon Sep 17 00:00:00 2001 From: Daniel Nelson Date: Tue, 26 Sep 2017 15:36:00 -0700 Subject: [PATCH] Fix parsing of JSON with a UTF8 BOM in httpjson (#3267) (cherry picked from commit 8614445235a4fb5cd9a56b895221cbdac3d1a59a) --- plugins/inputs/httpjson/httpjson.go | 7 ++++++- plugins/inputs/httpjson/httpjson_test.go | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/plugins/inputs/httpjson/httpjson.go b/plugins/inputs/httpjson/httpjson.go index ba5d7734d..f3edc57ba 100644 --- a/plugins/inputs/httpjson/httpjson.go +++ b/plugins/inputs/httpjson/httpjson.go @@ -1,6 +1,7 @@ package httpjson import ( + "bytes" "fmt" "io/ioutil" "net/http" @@ -15,6 +16,10 @@ import ( "github.com/influxdata/telegraf/plugins/parsers" ) +var ( + utf8BOM = []byte("\xef\xbb\xbf") +) + // HttpJson struct type HttpJson struct { Name string @@ -170,7 +175,6 @@ func (h *HttpJson) gatherServer( serverURL string, ) error { resp, responseTime, err := h.sendRequest(serverURL) - if err != nil { return err } @@ -266,6 +270,7 @@ func (h *HttpJson) sendRequest(serverURL string) (string, float64, error) { if err != nil { return string(body), responseTime, err } + body = bytes.TrimPrefix(body, utf8BOM) // Process response if resp.StatusCode != http.StatusOK { diff --git a/plugins/inputs/httpjson/httpjson_test.go b/plugins/inputs/httpjson/httpjson_test.go index 629da8b5f..60ee88b49 100644 --- a/plugins/inputs/httpjson/httpjson_test.go +++ b/plugins/inputs/httpjson/httpjson_test.go @@ -560,3 +560,18 @@ func TestHttpJsonArray200Tags(t *testing.T) { } } } + +var jsonBOM = []byte("\xef\xbb\xbf[{\"value\":17}]") + +// TestHttpJsonBOM tests that UTF-8 JSON with a BOM can be parsed +func TestHttpJsonBOM(t *testing.T) { + httpjson := genMockHttpJson(string(jsonBOM), 200) + + for _, service := range httpjson { + if service.Name == "other_webapp" { + var acc testutil.Accumulator + err := acc.GatherError(service.Gather) + require.NoError(t, err) + } + } +}