Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Gin Gonic + Socket IO
package main
import (
"fmt"
"github.com/gin-gonic/gin"
engineio "github.com/googollee/go-engine.io"
"github.com/googollee/go-engine.io/transport"
engineiopooling "github.com/googollee/go-engine.io/transport/polling"
socketio "github.com/googollee/go-socket.io"
"log"
"net/http"
"time"
)
func main() {
// Use Transport Pooling, because Websocket Transport still Error
server, err := socketio.NewServer(&engineio.Options{
Transports: []transport.Transport{
&engineiopooling.Transport{
Client: &http.Client{
Timeout: time.Minute,
},
},
},
})
if err != nil {
log.Fatal(err)
}
server.OnConnect("/", func(s socketio.Conn) error {
s.SetContext("")
fmt.Println("Connected:", s.ID())
return nil
})
server.OnEvent("/", "msg", func(s socketio.Conn, msg string) string {
fmt.Println("Receive Message : " + msg)
s.Emit("reply", "OK")
return "recv " + msg
})
server.OnDisconnect("/", func(s socketio.Conn, msg string) {
fmt.Println("Somebody just close the connection ")
})
go server.Serve()
defer server.Close()
// Create Setup
router := gin.Default()
// Combine Gin Gonic with Socket IO
// Method 1 using gin.WrapH or you changes this with server.ServeHTTP(Writer, Request)
router.GET("/socket.io/", gin.WrapH(server))
// Method 2 using server.ServerHTTP(Writer, Request) and also you can simply this by using gin.WrapH
router.POST("/socket.io/", func(context *gin.Context) {
server.ServeHTTP(context.Writer, context.Request)
})
// Run Gin
_ = router.Run(":8080")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment