websocket.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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/repositories"
  16. "sikey.com/websocket/server"
  17. "x.sikey.com.cn/serverx/dbx"
  18. "x.sikey.com.cn/serverx/gid"
  19. "x.sikey.com.cn/serverx/rdbx"
  20. )
  21. var name = flag.String("n", "w303", "the name of the server")
  22. var prot = flag.Int64("p", 8080, "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.toml", "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", *prot)
  31. log.Println("Server start at ", port)
  32. app := newApp()
  33. app.Run(fmt.Sprintf(":%d", prot))
  34. }
  35. func newApp() *gin.Engine {
  36. app := gin.Default()
  37. ginpprof.Wrap(app)
  38. gin.SetMode(config.GetEnvironment())
  39. id := serverId()
  40. srv := &server.Server{
  41. ID: id,
  42. Upgrader: websocket.Upgrader{
  43. ReadBufferSize: config.Websocket.ReadBufferSize,
  44. WriteBufferSize: config.Websocket.WriteBufferSize,
  45. CheckOrigin: func(r *http.Request) bool {
  46. return true
  47. },
  48. },
  49. Hub: server.NewHub(id),
  50. Repositories: repositories.NewRepositories(dbx.GetConnect(), rdbx.GetConnect()),
  51. }
  52. app.GET("/websocket/endpoint", func(ctx *gin.Context) { srv.WebsocketHandler(ctx) })
  53. app.GET("/websocket/clients", func(ctx *gin.Context) {
  54. clients := srv.Hub.GetClients()
  55. ctx.JSON(http.StatusOK, gin.H{"clients": clients})
  56. })
  57. return app
  58. }
  59. func serverId() string {
  60. var id string
  61. id, err := machineid.ID()
  62. if err != nil {
  63. id = uuid.NewString()
  64. } else {
  65. id = strings.ToLower(id)
  66. }
  67. return id
  68. }