websocket.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. app.GET("/websocket/clients", func(ctx *gin.Context) {
  51. clients := srv.Hub.GetClients()
  52. ctx.JSON(http.StatusOK, gin.H{"clients": clients})
  53. })
  54. return app
  55. }
  56. func serverId() string {
  57. var id string
  58. id, err := machineid.ID()
  59. if err != nil {
  60. id = uuid.NewString()
  61. } else {
  62. id = strings.ToLower(id)
  63. }
  64. return id
  65. }