Parcourir la source

Implement event encoding/decoding for JSON.

Arto Bendiken il y a 3 ans
Parent
commit
606f429491
2 fichiers modifiés avec 27 ajouts et 8 suppressions
  1. 12 3
      event.go
  2. 15 5
      event_test.go

+ 12 - 3
event.go

@@ -1,7 +1,9 @@
 package borealis
 
 import (
+	"encoding/base64"
 	"encoding/json"
+	"fmt"
 )
 
 type Event struct {
@@ -19,22 +21,29 @@ func (event Event) MarshalJSON() ([]byte, error) {
 		event.TimestampS,
 		event.TimestampMS,
 		event.SequentialID,
-		event.UniqueID,
+		event.UniqueID, // automatically Base64-encoded
 		event.Payload,
 	}
 	return json.Marshal(array)
 }
 
 func (event *Event) UnmarshalJSON(input []byte) error {
+	var err error
 	array := []interface{}{}
-	if err := json.Unmarshal(input, &array); err != nil {
+	if err = json.Unmarshal(input, &array); err != nil {
 		return err
 	}
+	if len(array) != 6 {
+		return fmt.Errorf("event must be an array of length 6, got %d", len(array))
+	}
 	event.Type = uint16(array[0].(float64))
 	event.TimestampS = uint32(array[1].(float64))
 	event.TimestampMS = uint16(array[2].(float64))
 	event.SequentialID = uint64(array[3].(float64))
-	event.UniqueID = array[4].([]byte)
+	event.UniqueID, err = base64.StdEncoding.DecodeString(array[4].(string))
+	if err != nil {
+		return err
+	}
 	event.Payload = array[5]
 	return nil
 }

+ 15 - 5
event_test.go

@@ -2,17 +2,27 @@ package borealis
 
 import (
 	"encoding/json"
+	"reflect"
 	"testing"
 )
 
+var event = Event{
+	Type:         1,
+	TimestampS:   2,
+	TimestampMS:  3,
+	SequentialID: 4,
+	UniqueID:     []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF},
+	Payload:      map[string]interface{}{},
+}
+var eventJSON = "[1,2,3,4,\"AAECAwQFBgcICQoLDA0ODw==\",{}]"
+
 func TestEncodeEvent(t *testing.T) {
-	event := Event{Type: 0x1234}
 	output, err := json.Marshal(event)
 	if err != nil {
 		t.Error(err)
 	}
 	actual := string(output)
-	expected := "[4660]"
+	expected := eventJSON
 	if actual != expected {
 		t.Errorf("expected %v, but got %v", expected, actual)
 	}
@@ -20,11 +30,11 @@ func TestEncodeEvent(t *testing.T) {
 
 func TestDecodeEvent(t *testing.T) {
 	var actual Event
-	if err := json.Unmarshal([]byte("[4660]"), &actual); err != nil {
+	if err := json.Unmarshal([]byte(eventJSON), &actual); err != nil {
 		t.Error(err)
 	}
-	expected := Event{Type: 0x1234}
-	if actual != expected {
+	expected := event
+	if !reflect.DeepEqual(actual, expected) {
 		t.Errorf("expected %v, but got %v", expected, actual)
 	}
 }