package main import ( "encoding/json" "log" "net/http" "time" "github.com/gin-gonic/gin" "github.com/gorilla/websocket" ) var upGrader = websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true }, } func main() { eg := gin.Default() eg.Use(Cors()) eg.GET("start", func(c *gin.Context) { c.JSON(0, gin.H{ "task": "ok", }) }) 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 } for { //读取ws中的数据 log.Println( "123", ) msg := gin.H{ "content": string(message), } data, err := json.Marshal(msg) if err != nil { log.Println(err) } //写入ws数据 err = ws.WriteMessage(mt, data) if err != nil { c.Error(err) break } time.Sleep(time.Second * 10) } }) eg.Run(":12203") }