package evio import "strings" type null[T any] struct { val T ok bool } type matcher struct { rawPattern string pattern string matchPrefix bool matchSuffix bool } // TODO 优化,使用缓存,只处理一次 func NewMatcher(pattern string) Matcher { m := matcher{ rawPattern: pattern, pattern: pattern, matchPrefix: strings.HasSuffix(pattern, ".*"), // foo.* matchSuffix: strings.HasPrefix(pattern, ".*"), // *.bar } if m.matchPrefix { m.pattern = pattern[:len(pattern)-1] } if m.matchSuffix { m.pattern = pattern[1:] } return &m } func (m *matcher) Match(topic string) bool { if m.rawPattern == topic { return true } hasPrefix := strings.HasPrefix(topic, m.pattern) hasSuffix := strings.HasSuffix(topic, m.pattern) hasMiddle := strings.Contains(topic, m.pattern) // *.bar.* if !m.matchPrefix && !m.matchSuffix { return hasMiddle && !hasPrefix && !hasSuffix } // foo.* if m.matchPrefix { return hasPrefix } // *.bar if m.matchSuffix { return hasSuffix } return false }