message with payload (serializable as JSON)
This commit is contained in:
parent
b813dd40db
commit
b4d9338353
2 changed files with 33 additions and 2 deletions
|
@ -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}
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue