websocket.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "strings"
  8. "time"
  9. "github.com/DeanThompson/ginpprof"
  10. "github.com/denisbrodbeck/machineid"
  11. "github.com/gin-gonic/gin"
  12. "github.com/google/uuid"
  13. "github.com/gorilla/websocket"
  14. "sikey.com/websocket/config"
  15. "sikey.com/websocket/pkg/dbx"
  16. "sikey.com/websocket/pkg/gid"
  17. "sikey.com/websocket/pkg/rdbx"
  18. "sikey.com/websocket/repositories"
  19. "sikey.com/websocket/server"
  20. )
  21. var name = flag.String("n", "w303", "the name of the server")
  22. var port = flag.Int64("p", 8081, "the port of the server")
  23. var nodeId = flag.Int64("i", 1, "the node id of the server")
  24. var configFile = flag.String("f", "./etc/websocket.debug.yaml", "the config file")
  25. func main() {
  26. time.Local = time.UTC
  27. flag.Parse()
  28. gid.SetNodeId(*nodeId)
  29. config.MustLoadConfig(*configFile)
  30. port := fmt.Sprintf(":%d", *port)
  31. log.Println("Server start at ", port)
  32. app := newApp()
  33. if err := app.Run(port); err != nil {
  34. log.Fatalln(err)
  35. }
  36. }
  37. func newApp() *gin.Engine {
  38. app := gin.Default()
  39. ginpprof.Wrap(app)
  40. gin.SetMode(config.GetEnvironment())
  41. id := serverId()
  42. srv := &server.Server{
  43. ID: id,
  44. Upgrader: websocket.Upgrader{
  45. ReadBufferSize: config.Websocket.ReadBufferSize,
  46. WriteBufferSize: config.Websocket.WriteBufferSize,
  47. CheckOrigin: func(r *http.Request) bool {
  48. return true
  49. },
  50. },
  51. Hub: server.NewHub(id),
  52. Repositories: repositories.NewRepositories(dbx.GetConnect(), rdbx.GetConnect()),
  53. }
  54. app.GET("/websocket/endpoint", func(ctx *gin.Context) { srv.WebsocketHandler(ctx) })
  55. app.GET("/websocket/clients", func(ctx *gin.Context) {
  56. clients := srv.Hub.GetClients()
  57. ctx.JSON(http.StatusOK, gin.H{"clients": clients})
  58. })
  59. return app
  60. }
  61. func serverId() string {
  62. var id string
  63. id, err := machineid.ID()
  64. if err != nil {
  65. id = uuid.NewString()
  66. } else {
  67. id = strings.ToLower(id)
  68. }
  69. return id
  70. }