event.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package borealis
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. )
  7. type Event struct {
  8. Type uint16
  9. TimestampS uint32
  10. TimestampMS uint16
  11. SequentialID uint64
  12. UniqueID []byte
  13. Payload interface{}
  14. }
  15. func (event Event) MarshalJSON() ([]byte, error) {
  16. array := []interface{}{
  17. event.Type,
  18. event.TimestampS,
  19. event.TimestampMS,
  20. event.SequentialID,
  21. event.UniqueID, // automatically Base64-encoded
  22. event.Payload,
  23. }
  24. return json.Marshal(array)
  25. }
  26. func (event *Event) UnmarshalJSON(input []byte) error {
  27. var err error
  28. array := []interface{}{}
  29. if err = json.Unmarshal(input, &array); err != nil {
  30. return err
  31. }
  32. if len(array) != 6 {
  33. return fmt.Errorf("event must be an array of length 6, got %d", len(array))
  34. }
  35. event.Type = uint16(array[0].(float64))
  36. event.TimestampS = uint32(array[1].(float64))
  37. event.TimestampMS = uint16(array[2].(float64))
  38. event.SequentialID = uint64(array[3].(float64))
  39. event.UniqueID, err = base64.StdEncoding.DecodeString(array[4].(string))
  40. if err != nil {
  41. return err
  42. }
  43. event.Payload = array[5]
  44. return nil
  45. }