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