websocket.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package main
  2. import (
  3. "embed"
  4. "encoding/json"
  5. "flag"
  6. "fmt"
  7. "log"
  8. "net/http"
  9. "strings"
  10. "time"
  11. "github.com/DeanThompson/ginpprof"
  12. "github.com/denisbrodbeck/machineid"
  13. "github.com/gin-gonic/gin"
  14. "github.com/google/uuid"
  15. "github.com/nicksnyder/go-i18n/v2/i18n"
  16. "github.com/spf13/viper"
  17. "golang.org/x/text/language"
  18. "sikey.com/websocket/config"
  19. "sikey.com/websocket/pkg/gid"
  20. "sikey.com/websocket/server"
  21. )
  22. var name = flag.String("n", "w303", "the name of the server")
  23. var port = flag.Int64("p", 8081, "the port of the server")
  24. var nodeId = flag.Int64("i", 1, "the node id of the server")
  25. var configFile = flag.String("f", "./etc/websocket.debug.yaml", "the config file")
  26. func main() {
  27. time.Local = time.UTC
  28. flag.Parse()
  29. gid.SetNodeId(*nodeId)
  30. config.MustLoadConfig(*configFile)
  31. port := fmt.Sprintf(":%d", *port)
  32. log.Println("Server start at ", port)
  33. app := newApp()
  34. if err := app.Run(port); err != nil {
  35. log.Fatalln(err)
  36. }
  37. }
  38. //go:embed locales/*.json
  39. var LocaleFS embed.FS
  40. func newApp() *gin.Engine {
  41. app := gin.Default()
  42. ginpprof.Wrap(app)
  43. gin.SetMode(gin.ReleaseMode)
  44. // bundle := &i18n.BundleCfg{
  45. // FormatBundleFile: viper.GetString("i18n.format_bundle_file"),
  46. // RootPath: viper.GetString("i18n.root_path"),
  47. // UnmarshalFunc: json.Unmarshal,
  48. // AcceptLanguage: []language.Tag{language.Chinese, language.English},
  49. // DefaultLanguage: language.English,
  50. // }
  51. // var localizeMiddleware = i18n.Localize(
  52. // i18n.WithGetLngHandle(middleware.Language()),
  53. // i18n.WithBundle(bundle),
  54. // )
  55. // app.Use(localizeMiddleware)
  56. srv := server.NewServer()
  57. app.GET("/websocket/endpoint", func(ctx *gin.Context) {
  58. // i18n
  59. rootPath := viper.GetString("i18n.root_path")
  60. bundle := i18n.NewBundle(language.English)
  61. bundle.RegisterUnmarshalFunc("json", json.Unmarshal)
  62. bundle.LoadMessageFile(rootPath + "/en.json")
  63. bundle.LoadMessageFile(rootPath + "/zh.json")
  64. // ctx.Set("bundle", bundle)
  65. srv.WebsocketHandler(ctx, bundle)
  66. })
  67. app.GET("/websocket/clients", func(ctx *gin.Context) {
  68. clients := srv.GetClients()
  69. ctx.JSON(http.StatusOK, gin.H{"clients": clients})
  70. })
  71. return app
  72. }
  73. func serverId() string {
  74. var id string
  75. id, err := machineid.ID()
  76. if err != nil {
  77. id = uuid.NewString()
  78. } else {
  79. id = strings.ToLower(id)
  80. }
  81. return id
  82. }