2023-01-10 08:37:57 +00:00
|
|
|
package ws
|
|
|
|
|
|
|
|
import (
|
2023-02-03 04:43:37 +00:00
|
|
|
"context"
|
2023-01-10 08:37:57 +00:00
|
|
|
"github.com/gin-gonic/gin"
|
2023-04-22 10:02:50 +00:00
|
|
|
"github.com/huoxue1/qinglong-go/internal/res"
|
2023-01-12 03:21:57 +00:00
|
|
|
"github.com/huoxue1/qinglong-go/service/client"
|
2023-02-03 04:43:37 +00:00
|
|
|
"nhooyr.io/websocket"
|
|
|
|
"nhooyr.io/websocket/wsjson"
|
|
|
|
"time"
|
2023-01-10 08:37:57 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func Api(group *gin.RouterGroup) {
|
|
|
|
group.GET("/info", info())
|
|
|
|
group.GET("/:id/:name/websocket", wsHandle())
|
|
|
|
}
|
|
|
|
|
|
|
|
func info() gin.HandlerFunc {
|
|
|
|
return func(ctx *gin.Context) {
|
2023-01-10 12:18:45 +00:00
|
|
|
ctx.JSON(200, gin.H{"websocket": true, "origins": []string{"*:*"}, "cookie_needed": false, "entropy": int64(3563341155)})
|
2023-01-10 08:37:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func wsHandle() gin.HandlerFunc {
|
|
|
|
return func(ctx *gin.Context) {
|
2023-02-03 04:43:37 +00:00
|
|
|
conn, err := websocket.Accept(ctx.Writer, ctx.Request, &websocket.AcceptOptions{
|
|
|
|
Subprotocols: nil,
|
|
|
|
InsecureSkipVerify: false,
|
|
|
|
OriginPatterns: []string{"*"},
|
|
|
|
CompressionMode: 0,
|
|
|
|
CompressionThreshold: 0,
|
|
|
|
})
|
2023-01-10 08:37:57 +00:00
|
|
|
if err != nil {
|
|
|
|
ctx.JSON(502, res.Err(502, err))
|
|
|
|
return
|
|
|
|
}
|
2023-01-12 03:21:57 +00:00
|
|
|
|
2023-02-03 04:43:37 +00:00
|
|
|
wsjson.Write(context.Background(), conn, map[string]string{"123": "11"})
|
|
|
|
wsjson.Write(context.Background(), conn, map[string]string{"123": "11"})
|
|
|
|
wsjson.Write(context.Background(), conn, map[string]string{"123": "11"})
|
|
|
|
|
|
|
|
c := make(chan any, 100)
|
|
|
|
client.AddChan(c)
|
|
|
|
|
|
|
|
for true {
|
|
|
|
wsjson.Write(context.Background(), conn, map[string]string{"123": "11"})
|
|
|
|
time.Sleep(1000)
|
|
|
|
wsjson.Write(context.Background(), conn, map[string]string{"123": "11"})
|
|
|
|
data := <-c
|
|
|
|
err := wsjson.Write(context.Background(), conn, data)
|
|
|
|
if err != nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2023-01-10 08:37:57 +00:00
|
|
|
}
|
2023-02-03 04:43:37 +00:00
|
|
|
|
2023-01-10 08:37:57 +00:00
|
|
|
}
|