From b4d9338353d4bd8cf8f25cda792cb88fac3e6c20 Mon Sep 17 00:00:00 2001 From: Helmut Merz Date: Wed, 5 Jul 2023 09:40:00 +0200 Subject: [PATCH] message with payload (serializable as JSON) --- lib/message/message.go | 22 ++++++++++++++++++++-- tests/unit_test.go | 13 +++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/lib/message/message.go b/lib/message/message.go index 5511515..324e5c7 100644 --- a/lib/message/message.go +++ b/lib/message/message.go @@ -1,9 +1,11 @@ package message import ( + "encoding/json" "strings" "git.sr.ht/~cco/go-scopes/lib" + "git.sr.ht/~cco/go-scopes/logging/log" ) // message head @@ -66,7 +68,7 @@ func (msg *message) WithPayload(p lib.Payload) lib.Message { return msg } -func NewMessage(args ...string) lib.Message { +func New(args ...string) lib.Message { args = append(args, "", "")[:4] return &message{ head: &head{ @@ -79,7 +81,23 @@ func NewMessage(args ...string) lib.Message { } func SimpleMessage(action string) lib.Message { - return NewMessage("standard", action) + return New("standard", action) } var Quit = SimpleMessage("quit") + +// payload + +type payload struct { + data interface{} +} + +func (pl payload) String() string { + b, err := json.Marshal(pl.data) + log.Err(err) + return string(b) +} + +func Payload(d interface{}) lib.Payload { + return payload{d} +} diff --git a/tests/unit_test.go b/tests/unit_test.go index 3120e87..61d8be2 100644 --- a/tests/unit_test.go +++ b/tests/unit_test.go @@ -13,6 +13,7 @@ func TestUnit(tb *tbase.T) { t := testing.SetUp(tb) t.Run("address", AddressTest) t.Run("message", MessageTest) + t.Run("payload", PayloadTest) } func AddressTest(t *testing.T) { @@ -41,4 +42,16 @@ func MessageTest(t *testing.T) { t.AssertEqual(msg.Action(), "doit") t.AssertEqual(msg.Head().Action(), "doit") t.AssertEqual(fmt.Sprint(msg), "standard/doit//") + msg = message.New("taskman", "doit", "task", "tsk001") + t.AssertEqual(fmt.Sprint(msg), "taskman/doit/task/tsk001") +} + +func PayloadTest(t *testing.T) { + msg := message.New("taskman", "doit", "task", "tsk001") + //pl := struct{ text, work string }{"scopes messaging", "development"} + pl1 := message.Payload(`development`) + t.AssertEqual(fmt.Sprint(pl1), `"development"`) + pl2 := message.Payload(map[string]string{"activity": "development"}) + t.AssertEqual(fmt.Sprint(pl2), `{"activity":"development"}`) + msg.WithPayload(pl2) }