Fix parsing of JSON with a UTF8 BOM in httpjson (#3267)

(cherry picked from commit 8614445235)
This commit is contained in:
Daniel Nelson 2017-09-26 15:36:00 -07:00 committed by Daniel Nelson
parent 5b791fd2e5
commit 8e7cf0109e
No known key found for this signature in database
GPG Key ID: CAAD59C9444F6155
2 changed files with 21 additions and 1 deletions

View File

@ -1,6 +1,7 @@
package httpjson package httpjson
import ( import (
"bytes"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
@ -15,6 +16,10 @@ import (
"github.com/influxdata/telegraf/plugins/parsers" "github.com/influxdata/telegraf/plugins/parsers"
) )
var (
utf8BOM = []byte("\xef\xbb\xbf")
)
// HttpJson struct // HttpJson struct
type HttpJson struct { type HttpJson struct {
Name string Name string
@ -170,7 +175,6 @@ func (h *HttpJson) gatherServer(
serverURL string, serverURL string,
) error { ) error {
resp, responseTime, err := h.sendRequest(serverURL) resp, responseTime, err := h.sendRequest(serverURL)
if err != nil { if err != nil {
return err return err
} }
@ -266,6 +270,7 @@ func (h *HttpJson) sendRequest(serverURL string) (string, float64, error) {
if err != nil { if err != nil {
return string(body), responseTime, err return string(body), responseTime, err
} }
body = bytes.TrimPrefix(body, utf8BOM)
// Process response // Process response
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {

View File

@ -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)
}
}
}