package mqtt_api import ( "time" ) type Context struct { // 主题 Topic string // 数据 Data []byte mqttClient *MqttClient handlers []Handler currentHandlerIndex int } func newContext(mqttClient *MqttClient, topic string, data []byte, handlers []Handler) (*Context, error) { return &Context{ Topic: topic, Data: data, mqttClient: mqttClient, handlers: handlers, currentHandlerIndex: 0, }, nil } func destroyContext(c *Context) { if c == nil { return } if c.currentHandlerIndex == len(c.handlers) { return } ticker := time.NewTicker(100 * time.Millisecond) defer ticker.Stop() for { select { case <-ticker.C: if c.currentHandlerIndex == len(c.handlers) { break } } } } func (c *Context) callHandlers() { c.currentHandlerIndex = 0 for c.currentHandlerIndex < len(c.handlers) { c.handlers[c.currentHandlerIndex](c) c.currentHandlerIndex++ } } func (c *Context) Response(responseIdentifier string, data []byte) error { err := c.mqttClient.response(c.Topic, responseIdentifier, data) if err != nil { return err } return nil } func (c *Context) Next() { c.currentHandlerIndex++ if c.currentHandlerIndex < len(c.handlers) { c.handlers[c.currentHandlerIndex](c) } }