57 lines
1.2 KiB
Go
57 lines
1.2 KiB
Go
package middleware
|
|
|
|
import (
|
|
"game-driver/internal/schema"
|
|
"game-driver/leaf"
|
|
"go.uber.org/zap"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// TimeoutOver 定时器中间件,用于定时触发屏幕打印和语音播报。 t 是语音播报实例
|
|
func TimeoutOver(maxTimeout int) leaf.HandlerFunc {
|
|
return func(c *leaf.Context) {
|
|
pm := leaf.Value[*schema.PlayModal](c, PayloadJSONKey)
|
|
|
|
// 定时器
|
|
var timer *time.Timer
|
|
if pm.Timeout != 0 {
|
|
timer = time.NewTimer(time.Second * time.Duration(pm.Timeout))
|
|
} else {
|
|
timer = time.NewTimer(time.Second * time.Duration(maxTimeout))
|
|
}
|
|
defer timer.Stop()
|
|
|
|
// 等待组
|
|
var wait sync.WaitGroup
|
|
defer wait.Wait()
|
|
|
|
// 结束信号通道
|
|
a := make(chan struct{})
|
|
// 发送结束信号
|
|
defer close(a)
|
|
|
|
cancel := leaf.WithCancel(c)
|
|
wait.Add(1)
|
|
go func() {
|
|
defer wait.Done()
|
|
|
|
zap.S().Infoln("超时 Timer 监控开始")
|
|
defer zap.S().Infoln("超时 Timer 监控结束")
|
|
|
|
// 结束标志
|
|
select {
|
|
case <-a:
|
|
case <-timer.C: // 定时器结束
|
|
{
|
|
zap.S().Infoln("超时 Timer 触发")
|
|
cancel()
|
|
leaf.WithValue[leaf.EndType](c, leaf.EndKey, leaf.EndTimeout)
|
|
}
|
|
}
|
|
}()
|
|
|
|
c.Next()
|
|
}
|
|
}
|