websocket.go 1.4 KB

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