65 lines
1.3 KiB
Go
65 lines
1.3 KiB
Go
package model
|
|
|
|
import (
|
|
"errors"
|
|
"strings"
|
|
)
|
|
|
|
type MqttTopic struct {
|
|
Project string
|
|
Domain string
|
|
DeviceType string
|
|
DeviceID string
|
|
Resource string
|
|
}
|
|
|
|
// 从字符串解析成 MqttTopic
|
|
func FromStringToMqttTopic(topic string) *MqttTopic {
|
|
parts := strings.Split(topic, "/")
|
|
// 补齐不足的部分
|
|
for len(parts) < 5 {
|
|
parts = append(parts, "")
|
|
}
|
|
return &MqttTopic{
|
|
Project: parts[0],
|
|
Domain: parts[1],
|
|
DeviceType: parts[2],
|
|
DeviceID: parts[3],
|
|
Resource: parts[4],
|
|
}
|
|
}
|
|
|
|
// 从结构体生成 topic 字符串,可用 "+" 表示通配符
|
|
func (m *MqttTopic) ToString() string {
|
|
toVal := func(s string) string {
|
|
if s == "" {
|
|
return "+"
|
|
}
|
|
return s
|
|
}
|
|
return strings.Join([]string{
|
|
toVal(m.Project),
|
|
toVal(m.Domain),
|
|
toVal(m.DeviceType),
|
|
toVal(m.DeviceID),
|
|
toVal(m.Resource),
|
|
}, "/")
|
|
}
|
|
|
|
// 严格生成 topic,不允许 "+" 或空
|
|
func (m *MqttTopic) Build() (string, error) {
|
|
parts := []string{m.Project, m.Domain, m.DeviceType, m.DeviceID, m.Resource}
|
|
for _, p := range parts {
|
|
if p == "" || p == "+" {
|
|
return "", errors.New("cannot build strict topic, wildcard exists")
|
|
}
|
|
}
|
|
return strings.Join(parts, "/"), nil
|
|
}
|
|
|
|
// 判断是否为通配符 topic
|
|
func (m *MqttTopic) IsWildcard() bool {
|
|
topic := m.ToString()
|
|
return strings.Contains(topic, "+") || strings.Contains(topic, "#")
|
|
}
|