hrtools/server/main.go

77 lines
1.1 KiB
Go

package main
import (
"encoding/json"
"log"
"net/http"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
var upGrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
var RemoteAddress = ":12203"
func init() {
log.SetFlags(log.Llongfile)
}
func main() {
eg := gin.Default()
eg.Use(Cors())
eg.GET("start", func(c *gin.Context) {
c.JSON(0, gin.H{
"task": "ok",
})
})
eg.POST("queue", PostPushQueue)
eg.GET("task", func(c *gin.Context) {
//升级get请求为webSocket协议
ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}
defer ws.Close()
mt, message, err := ws.ReadMessage()
if err != nil {
c.Error(err)
return
}
log.Println(string(message))
for {
//读取ws中的数据
log.Println(
"123",
)
task := taskQueue.PopBlock()
taskData, err := json.Marshal(task)
if err != nil {
log.Println(err, task)
continue
}
//写入ws数据
err = ws.WriteMessage(mt, taskData)
if err != nil {
log.Println(err)
break
}
}
})
eg.Run(":12203")
}