Skip to content

Commit a92123c

Browse files
authored
Accepting prefixed topic names (#84)
* Accepting prefixed topic named * Added a comment
1 parent 7175da5 commit a92123c

File tree

3 files changed

+25
-8
lines changed

3 files changed

+25
-8
lines changed

messaging/messaging.go

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,24 @@ type Message struct {
8181
Webpush *WebpushConfig `json:"webpush,omitempty"`
8282
APNS *APNSConfig `json:"apns,omitempty"`
8383
Token string `json:"token,omitempty"`
84-
Topic string `json:"topic,omitempty"`
84+
Topic string `json:"-"`
8585
Condition string `json:"condition,omitempty"`
8686
}
8787

88+
// MarshalJSON marshals a Message into JSON (for internal use only).
89+
func (m *Message) MarshalJSON() ([]byte, error) {
90+
// Create a new type to prevent infinite recursion.
91+
type messageInternal Message
92+
s := &struct {
93+
BareTopic string `json:"topic,omitempty"`
94+
*messageInternal
95+
}{
96+
BareTopic: strings.TrimPrefix(m.Topic, "/topics/"),
97+
messageInternal: (*messageInternal)(m),
98+
}
99+
return json.Marshal(s)
100+
}
101+
88102
// Notification is the basic notification template to use across all platforms.
89103
type Notification struct {
90104
Title string `json:"title,omitempty"`

messaging/messaging_test.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,11 @@ var validMessages = []struct {
6363
req: &Message{Topic: "test-topic"},
6464
want: map[string]interface{}{"topic": "test-topic"},
6565
},
66+
{
67+
name: "PrefixedTopicOnly",
68+
req: &Message{Topic: "/topics/test-topic"},
69+
want: map[string]interface{}{"topic": "test-topic"},
70+
},
6671
{
6772
name: "ConditionOnly",
6873
req: &Message{Condition: "test-condition"},
@@ -370,11 +375,11 @@ var invalidMessages = []struct {
370375
want: "exactly one of token, topic or condition must be specified",
371376
},
372377
{
373-
name: "InvalidTopicPrefix",
378+
name: "InvalidPrefixedTopicName",
374379
req: &Message{
375-
Topic: "/topics/foo",
380+
Topic: "/topics/",
376381
},
377-
want: "topic name must not contain the /topics/ prefix",
382+
want: "malformed topic name",
378383
},
379384
{
380385
name: "InvalidTopicName",

messaging/messaging_utils.go

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,8 @@ func validateMessage(message *Message) error {
3737

3838
// validate topic
3939
if message.Topic != "" {
40-
if strings.HasPrefix(message.Topic, "/topics/") {
41-
return fmt.Errorf("topic name must not contain the /topics/ prefix")
42-
}
43-
if !bareTopicNamePattern.MatchString(message.Topic) {
40+
bt := strings.TrimPrefix(message.Topic, "/topics/")
41+
if !bareTopicNamePattern.MatchString(bt) {
4442
return fmt.Errorf("malformed topic name")
4543
}
4644
}

0 commit comments

Comments
 (0)