封装websocket api

参考的相关文章 参考github的 example

golang 后台

 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
package ws

import (
	"github.com/gorilla/websocket"
	log "github.com/sirupsen/logrus"
	"net/http"
	"oj_backend1/core"
	"oj_backend1/util"
)
var upgrader = websocket.Upgrader{
	ReadBufferSize: 1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}
func reader(con *websocket.Conn) {
	var submit core.SubmitModel
	for  {
		msgType, p, err := con.ReadMessage()
		if err != nil {
			log.Printf("error %v",err)
			break
		}

	    util.JsonAsObj(p,&submit)
		log.Printf("submit := %v",submit)
		if err := con.WriteMessage(msgType,p); err!= nil {
			log.Printf("write err := %v",err)
			break
		}
	}
	con.Close()
}
func WsEndPointV1(w http.ResponseWriter, r*http.Request) {
	 ws, err := upgrader.Upgrade(w,r,nil)
	 if err != nil {
	 	log.Printf("error %v",err)
         return 
	 }
	 log.Println("connected ok ")
	 reader(ws)
}