37 lines
922 B
Go
37 lines
922 B
Go
package mqttingest
|
|
|
|
import "strings"
|
|
|
|
// TopicMatches reports whether a topic filter (with + or # wildcards) matches a topic name.
|
|
// It follows the MQTT v3.1.1 wildcard rules and supports shared subscriptions ($share).
|
|
func TopicMatches(filter, topic string) bool {
|
|
return matchTopic(routeSplit(filter), strings.Split(topic, "/"))
|
|
}
|
|
|
|
func matchTopic(route []string, topic []string) bool {
|
|
if len(route) == 0 {
|
|
return len(topic) == 0
|
|
}
|
|
if len(topic) == 0 {
|
|
return route[0] == "#"
|
|
}
|
|
if route[0] == "#" {
|
|
return true
|
|
}
|
|
if route[0] == "+" || route[0] == topic[0] {
|
|
return matchTopic(route[1:], topic[1:])
|
|
}
|
|
return false
|
|
}
|
|
|
|
// routeSplit removes $share/group/ when matching shared subscription filters.
|
|
func routeSplit(route string) []string {
|
|
if strings.HasPrefix(route, "$share/") {
|
|
parts := strings.Split(route, "/")
|
|
if len(parts) > 2 {
|
|
return parts[2:]
|
|
}
|
|
}
|
|
return strings.Split(route, "/")
|
|
}
|