websocket.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "time"
  8. "github.com/DeanThompson/ginpprof"
  9. "github.com/denisbrodbeck/machineid"
  10. "github.com/gin-gonic/gin"
  11. "github.com/google/uuid"
  12. "github.com/gorilla/websocket"
  13. "sikey.com/websocket/config"
  14. "sikey.com/websocket/repositories"
  15. "sikey.com/websocket/server"
  16. "sikey.com/websocket/utils/gid"
  17. "sikey.com/websocket/utils/mysqlx"
  18. "sikey.com/websocket/utils/redisx"
  19. "sikey.com/websocket/utils/zlog"
  20. )
  21. var configFile = flag.String("f", "./etc/websocket.toml", "the config file")
  22. var nodeId = flag.Int64("n", 1, "the node id")
  23. func main() {
  24. time.Local = time.UTC
  25. flag.Parse()
  26. config.MustLoadConfig(*configFile)
  27. gid.SetNodeId(*nodeId)
  28. // Zaplog init
  29. zlog.WithZapLogger(zlog.NewLogger(config.MustLoadLogger()))
  30. app := newApp()
  31. app.Run(fmt.Sprintf(":%d", config.Config.Port))
  32. }
  33. func newApp() *gin.Engine {
  34. app := gin.Default()
  35. ginpprof.Wrap(app)
  36. id := serverId()
  37. srv := &server.Server{
  38. ID: id,
  39. Upgrader: websocket.Upgrader{
  40. ReadBufferSize: config.Websocket.ReadBufferSize,
  41. WriteBufferSize: config.Websocket.WriteBufferSize,
  42. CheckOrigin: func(r *http.Request) bool {
  43. return true
  44. },
  45. },
  46. Hub: server.NewHub(id),
  47. Repositories: repositories.NewRepositories(mysqlx.ConnectMysql(), redisx.RedisConnect()),
  48. }
  49. app.GET("/websocket/endpoint", func(ctx *gin.Context) { srv.WebsocketHandler(ctx) })
  50. return app
  51. }
  52. func serverId() string {
  53. var id string
  54. id, err := machineid.ID()
  55. if err != nil {
  56. id = uuid.NewString()
  57. } else {
  58. id = strings.ToLower(id)
  59. }
  60. return id
  61. }