mirror of
https://github.com/Mrs4s/go-cqhttp.git
synced 2025-05-05 03:23:49 +08:00
server: simplify long poll implementation
This commit is contained in:
parent
111a5506b9
commit
810c781c25
@ -50,33 +50,37 @@ func longPolling(bot *coolq.CQBot, maxSize int) api.Handler {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
var (
|
var (
|
||||||
once sync.Once
|
ch = make(chan []interface{})
|
||||||
ch = make(chan []interface{}, 1)
|
|
||||||
timeout = time.Duration(p.Get("timeout").Int()) * time.Second
|
timeout = time.Duration(p.Get("timeout").Int()) * time.Second
|
||||||
)
|
)
|
||||||
defer close(ch)
|
|
||||||
go func() {
|
go func() {
|
||||||
mutex.Lock()
|
mutex.Lock()
|
||||||
defer mutex.Unlock()
|
defer mutex.Unlock()
|
||||||
if queue.Len() == 0 {
|
for queue.Len() == 0 {
|
||||||
cond.Wait()
|
cond.Wait()
|
||||||
}
|
}
|
||||||
once.Do(func() {
|
|
||||||
limit := int(p.Get("limit").Int())
|
limit := int(p.Get("limit").Int())
|
||||||
if limit <= 0 || queue.Len() < limit {
|
if limit <= 0 || queue.Len() < limit {
|
||||||
limit = queue.Len()
|
limit = queue.Len()
|
||||||
}
|
}
|
||||||
ret := make([]interface{}, limit)
|
ret := make([]interface{}, limit)
|
||||||
|
elem := queue.Front()
|
||||||
for i := 0; i < limit; i++ {
|
for i := 0; i < limit; i++ {
|
||||||
ret[i] = queue.Remove(queue.Front())
|
ret[i] = elem.Value
|
||||||
|
elem = elem.Next()
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case ch <- ret:
|
||||||
|
for i := 0; i < limit; i++ { // remove sent msg
|
||||||
|
queue.Remove(queue.Front())
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
// don't block if parent already return due to timeout
|
||||||
}
|
}
|
||||||
ch <- ret
|
|
||||||
})
|
|
||||||
}()
|
}()
|
||||||
if timeout != 0 {
|
if timeout != 0 {
|
||||||
select {
|
select {
|
||||||
case <-time.After(timeout):
|
case <-time.After(timeout):
|
||||||
once.Do(func() {})
|
|
||||||
return coolq.OK([]interface{}{})
|
return coolq.OK([]interface{}{})
|
||||||
case ret := <-ch:
|
case ret := <-ch:
|
||||||
return coolq.OK(ret)
|
return coolq.OK(ret)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user