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 44 45 46 47 48 49 50 51 52 53 54
| package main
import ( "log" "net/http" "time"
"github.com/gin-gonic/gin" "github.com/gorilla/websocket" )
var ( upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool { return true }, HandshakeTimeout: time.Duration(time.Second * 5), } )
func handleWebsocket(c *gin.Context) { conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) if err != nil { log.Println("cant upgrade connection:", err) return }
for { msgType, msgData, err := conn.ReadMessage() if err != nil { log.Println("cant read message:", err)
switch err.(type) { case *websocket.CloseError: return default: return } }
if msgType != websocket.TextMessage { continue }
log.Printf("incoming message: %s\n", msgData) } }
func main() { router := gin.Default() router.GET("/websocket", handleWebsocket) router.Run(":5000") }
|