websocket.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. "sikey.com/websocket/config"
  14. "sikey.com/websocket/pkg/gid"
  15. "sikey.com/websocket/server"
  16. )
  17. var name = flag.String("n", "w303", "the name of the server")
  18. var port = flag.Int64("p", 8081, "the port of the server")
  19. var nodeId = flag.Int64("i", 1, "the node id of the server")
  20. var configFile = flag.String("f", "./etc/websocket.debug.yaml", "the config file")
  21. func main() {
  22. time.Local = time.UTC
  23. flag.Parse()
  24. gid.SetNodeId(*nodeId)
  25. config.MustLoadConfig(*configFile)
  26. port := fmt.Sprintf(":%d", *port)
  27. log.Println("Server start at ", port)
  28. app := newApp()
  29. if err := app.Run(port); err != nil {
  30. log.Fatalln(err)
  31. }
  32. }
  33. func newApp() *gin.Engine {
  34. app := gin.Default()
  35. ginpprof.Wrap(app)
  36. gin.SetMode(gin.ReleaseMode)
  37. srv := server.NewServer()
  38. app.GET("/websocket/endpoint", func(ctx *gin.Context) { srv.WebsocketHandler(ctx) })
  39. app.GET("/websocket/clients", func(ctx *gin.Context) {
  40. clients := srv.GetClients()
  41. ctx.JSON(http.StatusOK, gin.H{"clients": clients})
  42. })
  43. return app
  44. }
  45. func serverId() string {
  46. var id string
  47. id, err := machineid.ID()
  48. if err != nil {
  49. id = uuid.NewString()
  50. } else {
  51. id = strings.ToLower(id)
  52. }
  53. return id
  54. }