forked from MartialBE/one-hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_channel.go
101 lines (87 loc) · 1.87 KB
/
check_channel.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package controller
import (
"io"
"net/http"
"one-api/common"
"one-api/common/requester"
"one-api/controller/check_channel"
"time"
"github.com/gin-gonic/gin"
)
func CheckImg(c *gin.Context) {
id := c.Param("id")
if id == "" {
c.AbortWithStatus(http.StatusNotFound)
return
}
err := check_channel.AppendAccessRecord(id, c)
if err != nil {
c.AbortWithStatus(http.StatusNotFound)
return
}
check_channel.CheckImageResponse(c)
}
type checkChannelRequest struct {
ID int `json:"id"`
Models string `json:"models"`
}
func CheckChannel(c *gin.Context) {
var params checkChannelRequest
if err := c.ShouldBindJSON(¶ms); err != nil {
common.APIRespondWithError(c, http.StatusOK, err)
return
}
ck, err := check_channel.CreateCheckChannel(params.ID, params.Models)
if err != nil {
common.APIRespondWithError(c, http.StatusOK, err)
return
}
// 设置 SSE 头信息
requester.SetEventStreamHeaders(c)
// 创建一个通道用于接收结果
resultChan := make(chan *check_channel.ModelResult)
heartbeatChan := make(chan bool)
doneChan := make(chan bool)
// 启动检查过程
go ck.RunStream(resultChan, doneChan)
// 启动心跳协程
go func() {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
heartbeatChan <- true
case <-doneChan:
return
}
}
}()
// 处理结果流
clientGone := c.Request.Context().Done()
c.Stream(func(w io.Writer) bool {
select {
case result := <-resultChan:
c.SSEvent("message", gin.H{
"type": "result",
"data": result,
})
return true
case <-heartbeatChan:
c.SSEvent("message", gin.H{
"type": "heartbeat",
"data": "ping",
})
return true
case <-doneChan:
c.SSEvent("message", gin.H{
"type": "done",
"data": "completed",
})
return false
case <-clientGone:
close(doneChan)
return false
}
})
}