package main import ( "embed" "encoding/json" "flag" "fmt" "log" "net/http" "strings" "time" "github.com/DeanThompson/ginpprof" "github.com/denisbrodbeck/machineid" "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/nicksnyder/go-i18n/v2/i18n" "github.com/spf13/viper" "golang.org/x/text/language" "sikey.com/websocket/config" "sikey.com/websocket/pkg/gid" "sikey.com/websocket/server" ) var name = flag.String("n", "w303", "the name of the server") var port = flag.Int64("p", 8081, "the port of the server") var nodeId = flag.Int64("i", 1, "the node id of the server") var configFile = flag.String("f", "./etc/websocket.debug.yaml", "the config file") func main() { time.Local = time.UTC flag.Parse() gid.SetNodeId(*nodeId) config.MustLoadConfig(*configFile) port := fmt.Sprintf(":%d", *port) log.Println("Server start at ", port) app := newApp() if err := app.Run(port); err != nil { log.Fatalln(err) } } //go:embed locales/*.json var LocaleFS embed.FS func newApp() *gin.Engine { app := gin.Default() ginpprof.Wrap(app) gin.SetMode(gin.ReleaseMode) // bundle := &i18n.BundleCfg{ // FormatBundleFile: viper.GetString("i18n.format_bundle_file"), // RootPath: viper.GetString("i18n.root_path"), // UnmarshalFunc: json.Unmarshal, // AcceptLanguage: []language.Tag{language.Chinese, language.English}, // DefaultLanguage: language.English, // } // var localizeMiddleware = i18n.Localize( // i18n.WithGetLngHandle(middleware.Language()), // i18n.WithBundle(bundle), // ) // app.Use(localizeMiddleware) srv := server.NewServer() app.GET("/websocket/endpoint", func(ctx *gin.Context) { // i18n rootPath := viper.GetString("i18n.root_path") bundle := i18n.NewBundle(language.English) bundle.RegisterUnmarshalFunc("json", json.Unmarshal) bundle.LoadMessageFile(rootPath + "/en.json") bundle.LoadMessageFile(rootPath + "/zh.json") // ctx.Set("bundle", bundle) srv.WebsocketHandler(ctx, bundle) }) app.GET("/websocket/clients", func(ctx *gin.Context) { clients := srv.GetClients() ctx.JSON(http.StatusOK, gin.H{"clients": clients}) }) return app } func serverId() string { var id string id, err := machineid.ID() if err != nil { id = uuid.NewString() } else { id = strings.ToLower(id) } return id }