message with payload (serializable as JSON)

This commit is contained in:
Helmut Merz 2023-07-05 09:40:00 +02:00
parent b813dd40db
commit b4d9338353
2 changed files with 33 additions and 2 deletions

View file

@ -1,9 +1,11 @@
package message package message
import ( import (
"encoding/json"
"strings" "strings"
"git.sr.ht/~cco/go-scopes/lib" "git.sr.ht/~cco/go-scopes/lib"
"git.sr.ht/~cco/go-scopes/logging/log"
) )
// message head // message head
@ -66,7 +68,7 @@ func (msg *message) WithPayload(p lib.Payload) lib.Message {
return msg return msg
} }
func NewMessage(args ...string) lib.Message { func New(args ...string) lib.Message {
args = append(args, "", "")[:4] args = append(args, "", "")[:4]
return &message{ return &message{
head: &head{ head: &head{
@ -79,7 +81,23 @@ func NewMessage(args ...string) lib.Message {
} }
func SimpleMessage(action string) lib.Message { func SimpleMessage(action string) lib.Message {
return NewMessage("standard", action) return New("standard", action)
} }
var Quit = SimpleMessage("quit") 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}
}

View file

@ -13,6 +13,7 @@ func TestUnit(tb *tbase.T) {
t := testing.SetUp(tb) t := testing.SetUp(tb)
t.Run("address", AddressTest) t.Run("address", AddressTest)
t.Run("message", MessageTest) t.Run("message", MessageTest)
t.Run("payload", PayloadTest)
} }
func AddressTest(t *testing.T) { func AddressTest(t *testing.T) {
@ -41,4 +42,16 @@ func MessageTest(t *testing.T) {
t.AssertEqual(msg.Action(), "doit") t.AssertEqual(msg.Action(), "doit")
t.AssertEqual(msg.Head().Action(), "doit") t.AssertEqual(msg.Head().Action(), "doit")
t.AssertEqual(fmt.Sprint(msg), "standard/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)
} }