1 Commits

Author SHA1 Message Date
Adrian Zuercher
e99fd0710b new subsrcribe topic with wildcard * 2025-08-24 07:52:26 +02:00
2 changed files with 22 additions and 3 deletions

View File

@@ -5,6 +5,7 @@ import (
"sync" "sync"
"gitea.tecamino.com/paadi/pubSub/models" "gitea.tecamino.com/paadi/pubSub/models"
"gitea.tecamino.com/paadi/pubSub/utils"
) )
// Pubsub implements a simple topic-based publish/subscribe system // Pubsub implements a simple topic-based publish/subscribe system
@@ -43,9 +44,13 @@ func (ps *Pubsub) worker() {
defer ps.wg.Done() defer ps.wg.Done()
for job := range ps.jobQueue { for job := range ps.jobQueue {
ps.mu.RLock() ps.mu.RLock()
subs := make([]func(any), 0, len(ps.subs[job.Topic])) var subs []func(any)
for _, cb := range ps.subs[job.Topic] { for pattern, callbacks := range ps.subs {
subs = append(subs, cb) if utils.Matches(pattern, job.Topic) {
for _, cb := range callbacks {
subs = append(subs, cb)
}
}
} }
ps.mu.RUnlock() ps.mu.RUnlock()

14
utils/utils.go Normal file
View File

@@ -0,0 +1,14 @@
package utils
import "strings"
func Matches(pattern, topic string) bool {
if pattern == "*" {
return true
}
if strings.HasSuffix(pattern, "/*") {
prefix := strings.TrimSuffix(pattern, "/*")
return strings.HasPrefix(topic, prefix+"/")
}
return pattern == topic
}