Created
January 4, 2020 23:10
-
-
Save supanadit/f6de65fc5896e8bb0c4656e451387d0f to your computer and use it in GitHub Desktop.
Gin Gonic + Socket IO
This file contains 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 | |
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") | |
} |
not working with new socket io version API
not working with new socket io version API
Latest supported version seems to be 1.4.x of socketio. 2.x is not supported.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That you for this!