1
0
mirror of https://github.com/Mrs4s/go-cqhttp.git synced 2025-05-04 19:17:37 +08:00

server: simplify long poll implementation

This commit is contained in:
wdvxdr 2022-05-25 14:19:59 +08:00
parent 111a5506b9
commit 810c781c25
No known key found for this signature in database
GPG Key ID: 703F8C071DE7A1B6

View File

@ -50,33 +50,37 @@ func longPolling(bot *coolq.CQBot, maxSize int) api.Handler {
return nil
}
var (
once sync.Once
ch = make(chan []interface{}, 1)
ch = make(chan []interface{})
timeout = time.Duration(p.Get("timeout").Int()) * time.Second
)
defer close(ch)
go func() {
mutex.Lock()
defer mutex.Unlock()
if queue.Len() == 0 {
for queue.Len() == 0 {
cond.Wait()
}
once.Do(func() {
limit := int(p.Get("limit").Int())
if limit <= 0 || queue.Len() < limit {
limit = queue.Len()
limit := int(p.Get("limit").Int())
if limit <= 0 || queue.Len() < limit {
limit = queue.Len()
}
ret := make([]interface{}, limit)
elem := queue.Front()
for i := 0; i < limit; i++ {
ret[i] = elem.Value
elem = elem.Next()
}
select {
case ch <- ret:
for i := 0; i < limit; i++ { // remove sent msg
queue.Remove(queue.Front())
}
ret := make([]interface{}, limit)
for i := 0; i < limit; i++ {
ret[i] = queue.Remove(queue.Front())
}
ch <- ret
})
default:
// don't block if parent already return due to timeout
}
}()
if timeout != 0 {
select {
case <-time.After(timeout):
once.Do(func() {})
return coolq.OK([]interface{}{})
case ret := <-ch:
return coolq.OK(ret)