2 Star 1 Fork 0

法马智慧/fmgo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
engine.go 1.89 KB
一键复制 编辑 原始数据 按行查看 历史
零海 提交于 2023-05-22 11:01 . emq5简化单个topic注册流程
package emq5
import (
"strings"
)
type Engine struct {
*Options
Topic string
TopicLen int
Wildcard bool
Shared bool
ShareGroup string
Qos int
}
func (o *Options) NewEngine(topic string, wildcard bool, qos int) (eng *Engine) {
eng = &Engine{
Options: o,
Topic: topic,
Wildcard: wildcard,
Qos: qos,
}
eng.checkTopic()
o.Engine = append(o.Engine, eng)
return
}
func (o *Options) NewSingleEngine(topic string, wildcard bool, qos int, handler Handler) {
eng := &Engine{
Options: o,
Topic: topic,
Qos: qos,
}
eng.checkTopic()
o.Engine = append(o.Engine, eng)
eng.Register("", handler)
return
}
func (e *Engine) checkTopic() {
if e.Topic[0] == '/' {
e.Logger.Error("topic禁止以'/'符号开头")
return
}
if e.Topic[len(e.Topic)-1] == '/' {
e.Logger.Error("topic禁止以'/'符号开头")
return
}
e.TopicLen = len(strings.Split(e.Topic, "/"))
}
// Register 注册方法到前缀树
func (e *Engine) Register(url string, handler Handler) {
e.checkUrl(url)
topic := e.Topic + url
if handler == nil {
e.Logger.Error("此topic未绑定方法")
return
}
path := e.splitUrl(topic)
for i, s := range path {
if s == "" {
path = append(path[:i], path[i+1:]...)
}
}
e.Options.node = e.Options.node.addRoute(path, handler)
}
// WithShare 注册共享订阅
func (e *Engine) WithShare(group string) {
e.Shared = true
e.ShareGroup = group
if group == "" {
e.ShareGroup = "default"
}
}
func (e *Engine) splitUrl(url string) []string {
urlList := strings.Split(url, "/")
for i, s := range urlList {
if s == "" {
urlList = append(urlList[:i], urlList[i+1:]...)
}
}
return urlList
}
func (e *Engine) checkUrl(url string) {
if url == "" {
return
}
if url[0] != '/' {
e.Logger.Error("路由必须以'/'符号开头")
return
}
if url[len(url)-1] == '/' {
e.Logger.Error("路由禁止以'/'符号开头")
return
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/fmpt/fmgo.git
git@gitee.com:fmpt/fmgo.git
fmpt
fmgo
fmgo
v1.5.8

搜索帮助