payload improvements: methods, conversions
This commit is contained in:
parent
31bdedc031
commit
4ad87d635c
3 changed files with 17 additions and 8 deletions
|
@ -82,7 +82,8 @@ type Address interface {
|
||||||
|
|
||||||
type Payload interface {
|
type Payload interface {
|
||||||
fmt.Stringer
|
fmt.Stringer
|
||||||
//Data() interface{}
|
Data() interface{}
|
||||||
|
FromJson(string) Payload
|
||||||
}
|
}
|
||||||
|
|
||||||
// action
|
// action
|
||||||
|
|
|
@ -100,15 +100,23 @@ func (pl *payload) String() string {
|
||||||
return string(b)
|
return string(b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (pl *payload) Data() interface{} {
|
||||||
|
return pl.data
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pl *payload) FromJson(s string) lib.Payload {
|
||||||
|
err := json.Unmarshal([]byte(s), &pl.data)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Msg("payload.FromJson()")
|
||||||
|
}
|
||||||
|
return pl
|
||||||
|
}
|
||||||
|
|
||||||
func Payload(d interface{}) lib.Payload {
|
func Payload(d interface{}) lib.Payload {
|
||||||
return &payload{d}
|
return &payload{d}
|
||||||
}
|
}
|
||||||
|
|
||||||
func FromJson[T any](s string) lib.Payload {
|
func PayloadFromJson[T any](s string) lib.Payload {
|
||||||
pl := &payload{new(T)}
|
pl := &payload{new(T)}
|
||||||
err := json.Unmarshal([]byte(s), &pl.data)
|
return pl.FromJson(s)
|
||||||
if err != nil {
|
|
||||||
log.Error().Err(err).Msg("payload: FromJson()")
|
|
||||||
}
|
|
||||||
return pl
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -54,6 +54,6 @@ func PayloadTest(t *testing.T) {
|
||||||
pl2 := message.Payload(map[string]string{"activity": "development"})
|
pl2 := message.Payload(map[string]string{"activity": "development"})
|
||||||
t.AssertEqual(fmt.Sprint(pl2), `{"activity":"development"}`)
|
t.AssertEqual(fmt.Sprint(pl2), `{"activity":"development"}`)
|
||||||
msg.WithPayload(pl2)
|
msg.WithPayload(pl2)
|
||||||
pl3 := message.FromJson[map[string]any](`{"activity": "development"}`)
|
pl3 := message.PayloadFromJson[map[string]any](`{"activity": "development"}`)
|
||||||
t.AssertEqual(fmt.Sprint(pl3), `{"activity":"development"}`)
|
t.AssertEqual(fmt.Sprint(pl3), `{"activity":"development"}`)
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue