websocket.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "net/http"
  6. "time"
  7. "github.com/DeanThompson/ginpprof"
  8. "github.com/gin-gonic/gin"
  9. "github.com/google/uuid"
  10. "github.com/gorilla/websocket"
  11. "github.com/redis/go-redis/v9"
  12. "sikey.com/websocket/config"
  13. "sikey.com/websocket/repositories"
  14. "sikey.com/websocket/server"
  15. "sikey.com/websocket/utils/mysqlx"
  16. "sikey.com/websocket/utils/zlog"
  17. )
  18. var configFile = flag.String("f", "./etc/websocket.toml", "the config file")
  19. func main() {
  20. flag.Parse()
  21. config.MustLoadConfig(*configFile)
  22. // Zaplog init
  23. zlog.WithZapLogger(zlog.NewLogger(config.MustLoadLogger()))
  24. app := newApp()
  25. app.Run(fmt.Sprintf(":%d", config.Config.Port))
  26. }
  27. func newApp() *gin.Engine {
  28. app := gin.Default()
  29. ginpprof.Wrap(app)
  30. hub := server.NewHub(server.HubConfig{
  31. ServerId: uuid.NewString(),
  32. Rdb: redis.NewUniversalClient(&redis.UniversalOptions{
  33. Addrs: []string{"106.75.230.4:6379"},
  34. Password: "sikey!Q@W#E456",
  35. DB: 0,
  36. }),
  37. ConnectSize: 1024,
  38. DisconnectSize: 1024,
  39. MessageSize: 125,
  40. })
  41. srv := &server.Server{
  42. Upgrader: websocket.Upgrader{
  43. ReadBufferSize: 1024,
  44. WriteBufferSize: 1024,
  45. CheckOrigin: func(r *http.Request) bool {
  46. return true
  47. },
  48. },
  49. WriteWait: 10 * time.Second,
  50. ReadWait: 10 * time.Second,
  51. PingWait: 120 * time.Second,
  52. Hub: hub,
  53. Repositories: repositories.NewRepositories(mysqlx.ConnectMysql()),
  54. }
  55. app.GET("/websocket/endpoint", func(ctx *gin.Context) { server.WebsocketHandler(ctx, srv) })
  56. app.GET("/index", func(ctx *gin.Context) {
  57. clients := hub.GetClients()
  58. ctx.JSON(http.StatusOK, gin.H{
  59. "clients": len(clients),
  60. })
  61. })
  62. return app
  63. }