websocket.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. if config.Config.Environment == "release" {
  30. gin.SetMode(gin.ReleaseMode)
  31. zlog.WithZapLogger(zlog.NewSLSLogger(zlog.SLSWriterConfig{
  32. Endpoint: config.SLS.Endpoint,
  33. AccessKeyId: config.SLS.AccessKeyId,
  34. AccessKeySecret: config.SLS.AccessKeySecret,
  35. ProjectName: config.SLS.ProjectName,
  36. LogStoreName: config.SLS.LogStoreName,
  37. Topic: config.SLS.Topic,
  38. SourceIP: config.SLS.SourceIP,
  39. Environment: config.Config.Environment,
  40. }))
  41. } else {
  42. zlog.WithZapLogger(zlog.NewLogger(config.MustLoadLogger()))
  43. }
  44. app := newApp()
  45. app.Run(fmt.Sprintf(":%d", config.Config.Port))
  46. }
  47. func newApp() *gin.Engine {
  48. app := gin.Default()
  49. ginpprof.Wrap(app)
  50. id := serverId()
  51. srv := &server.Server{
  52. ID: id,
  53. Upgrader: websocket.Upgrader{
  54. ReadBufferSize: config.Websocket.ReadBufferSize,
  55. WriteBufferSize: config.Websocket.WriteBufferSize,
  56. CheckOrigin: func(r *http.Request) bool {
  57. return true
  58. },
  59. },
  60. Hub: server.NewHub(id),
  61. Repositories: repositories.NewRepositories(mysqlx.Connect(), redisx.RedisConnect()),
  62. }
  63. app.GET("/websocket/endpoint", func(ctx *gin.Context) { srv.WebsocketHandler(ctx) })
  64. app.GET("/websocket/clients", func(ctx *gin.Context) {
  65. clients := srv.Hub.GetClients()
  66. ctx.JSON(http.StatusOK, gin.H{"clients": clients})
  67. })
  68. return app
  69. }
  70. func serverId() string {
  71. var id string
  72. id, err := machineid.ID()
  73. if err != nil {
  74. id = uuid.NewString()
  75. } else {
  76. id = strings.ToLower(id)
  77. }
  78. return id
  79. }