websocket.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. "x.sikey.com.cn/serverx/dbx"
  17. "x.sikey.com.cn/serverx/rdbx"
  18. )
  19. var configFile = flag.String("f", "./etc/websocket.toml", "the config file")
  20. func main() {
  21. time.Local = time.UTC
  22. flag.Parse()
  23. config.MustLoadConfig(*configFile)
  24. app := newApp()
  25. app.Run(fmt.Sprintf(":%d", config.GetServerPort()))
  26. }
  27. func newApp() *gin.Engine {
  28. app := gin.Default()
  29. ginpprof.Wrap(app)
  30. id := serverId()
  31. srv := &server.Server{
  32. ID: id,
  33. Upgrader: websocket.Upgrader{
  34. ReadBufferSize: config.Websocket.ReadBufferSize,
  35. WriteBufferSize: config.Websocket.WriteBufferSize,
  36. CheckOrigin: func(r *http.Request) bool {
  37. return true
  38. },
  39. },
  40. Hub: server.NewHub(id),
  41. Repositories: repositories.NewRepositories(dbx.GetConnect(), rdbx.GetConnect()),
  42. }
  43. app.GET("/websocket/endpoint", func(ctx *gin.Context) { srv.WebsocketHandler(ctx) })
  44. app.GET("/websocket/clients", func(ctx *gin.Context) {
  45. clients := srv.Hub.GetClients()
  46. ctx.JSON(http.StatusOK, gin.H{"clients": clients})
  47. })
  48. return app
  49. }
  50. func serverId() string {
  51. var id string
  52. id, err := machineid.ID()
  53. if err != nil {
  54. id = uuid.NewString()
  55. } else {
  56. id = strings.ToLower(id)
  57. }
  58. return id
  59. }