Skip to content

Commit

Permalink
Return error on field type mismatch (Graylog2#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
xose authored and Marius Sturm committed Mar 26, 2018
1 parent 4143646 commit 4dbb9d7
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 7 deletions.
23 changes: 16 additions & 7 deletions gelf/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gelf
import (
"bytes"
"encoding/json"
"fmt"
"time"
)

Expand Down Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions gelf/message_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}

}

0 comments on commit 4dbb9d7

Please sign in to comment.