qinglong-go/api/ws/ws.go

58 lines
1.4 KiB
Go
Raw Normal View History

package ws
import (
2023-02-03 04:43:37 +00:00
"context"
"github.com/gin-gonic/gin"
2023-01-12 03:21:57 +00:00
"github.com/huoxue1/qinglong-go/service/client"
"github.com/huoxue1/qinglong-go/utils/res"
2023-02-03 04:43:37 +00:00
"nhooyr.io/websocket"
"nhooyr.io/websocket/wsjson"
"time"
)
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)})
}
}
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,
})
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-02-03 04:43:37 +00:00
}