From 4dbb9d7213480a8484c02610e3f51ecd9c506a71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Mart=C3=ADnez?= Date: Mon, 26 Mar 2018 15:34:23 +0200 Subject: [PATCH] Return error on field type mismatch (#20) --- gelf/message.go | 23 ++++++++++++++++------- gelf/message_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 7 deletions(-) create mode 100644 gelf/message_test.go diff --git a/gelf/message.go b/gelf/message.go index 4e5a05e..414b1f9 100644 --- a/gelf/message.go +++ b/gelf/message.go @@ -3,6 +3,7 @@ package gelf import ( "bytes" "encoding/json" + "fmt" "time" ) @@ -84,21 +85,29 @@ func (m *Message) UnmarshalJSON(data []byte) error { m.Extra[k] = v continue } + + ok := true switch k { case "version": - m.Version = v.(string) + m.Version, ok = v.(string) case "host": - m.Host = v.(string) + m.Host, ok = v.(string) case "short_message": - m.Short = v.(string) + m.Short, ok = v.(string) case "full_message": - m.Full = v.(string) + m.Full, ok = v.(string) case "timestamp": - m.TimeUnix = v.(float64) + m.TimeUnix, ok = v.(float64) case "level": - m.Level = int32(v.(float64)) + var level float64 + level, ok = v.(float64) + m.Level = int32(level) case "facility": - m.Facility = v.(string) + m.Facility, ok = v.(string) + } + + if !ok { + return fmt.Errorf("invalid type for field %s", k) } } return nil diff --git a/gelf/message_test.go b/gelf/message_test.go new file mode 100644 index 0000000..d9260cf --- /dev/null +++ b/gelf/message_test.go @@ -0,0 +1,27 @@ +package gelf + +import ( + "encoding/json" + "testing" +) + +func TestWrongFieldTypes(t *testing.T) { + msgData := map[string]string{ + "version": `{"version": 1.1}`, + "host": `{"host": ["a", "b"]}`, + "short_message": `{"short_message": {"a": "b"}}`, + "full_message": `{"full_message": null}`, + "timestamp": `{"timestamp": "12345"}`, + "level": `{"level": false}`, + "facility": `{"facility": true}`, + } + + for k, j := range msgData { + var msg Message + err := json.Unmarshal([]byte(j), &msg) + if err == nil { + t.Errorf("expected type error on field %s", k) + } + } + +}