websocket.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. gin.SetMode(config.GetEnvironment())
  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(dbx.GetConnect(), rdbx.GetConnect()),
  43. }
  44. app.GET("/websocket/endpoint", func(ctx *gin.Context) { srv.WebsocketHandler(ctx) })
  45. app.GET("/websocket/clients", func(ctx *gin.Context) {
  46. clients := srv.Hub.GetClients()
  47. ctx.JSON(http.StatusOK, gin.H{"clients": clients})
  48. })
  49. return app
  50. }
  51. func serverId() string {
  52. var id string
  53. id, err := machineid.ID()
  54. if err != nil {
  55. id = uuid.NewString()
  56. } else {
  57. id = strings.ToLower(id)
  58. }
  59. return id
  60. }