Last active
March 14, 2020 08:59
-
-
Save sharvell/d86ca8bf98a7b1591f6d to your computer and use it in GitHub Desktop.
gin and socket.io
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| /* | |
| Like Snoops Gin and Juice, but gin and socket.io... | |
| https://github.com/gin-gonic/gin/issues/124 | |
| */ | |
| var Socketio_Server * socketio.Server | |
| func main() { | |
| var router_engine = gin.Default () | |
| var err error | |
| Socketio_Server, err = socketio.NewServer(nil) | |
| if err != nil { | |
| panic ( err ) | |
| } | |
| router_engine.GET ( "/", IndexHandler ) | |
| router_engine.Static ( "/public", "./public" ) | |
| router_engine.GET ( "/socket.io", socketHandler ) | |
| router_engine.POST ( "/socket.io", socketHandler ) | |
| router_engine.Handle ( "WS", "/socket.io", [] gin.HandlerFunc { socketHandler } ) | |
| router_engine.Handle ( "WSS", "/socket.io", [] gin.HandlerFunc { socketHandler } ) | |
| router_engine.Run(":8000") | |
| } | |
| func socketHandler ( c * gin.Context ) { | |
| Socketio_Server.On("connection", func(so socketio.Socket) { | |
| fmt.Println("on connection") | |
| so.Join("chat") | |
| so.On("chat message", func(msg string) { | |
| fmt.Println("emit:", so.Emit("chat message", msg)) | |
| so.BroadcastTo("chat", "chat message", msg) | |
| }) | |
| so.On("disconnection", func() { | |
| fmt.Println("on disconnect") | |
| }) | |
| }) | |
| Socketio_Server.On ( "error", func( so socketio.Socket, err error) { | |
| fmt.Printf ( "[ WebSocket ] Error : %v", err.Error () ) | |
| }) | |
| Socketio_Server.ServeHTTP ( c.Writer, c.Request ) | |
| } |
same here
just replace []gin.HandlerFunc with gin.WrapF(socketHandler)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I am getting the following error, did the Gin API change? I have spent way too long messing with this snippet trying to figure out what is going on. Any ideas?