// Run starts the back end. func Run() { flag.Parse() if !*debug { log.SetOutput(ioutil.Discard) } wg.Add(1) hub.SetTimeout(time.Second * 10) go hub.Run() go gs.Run() setupSchedulerCallbacks() games := getAvailableGames() names := getListOfGameNames(games) addGamesToScheduler(games) exists := false if *game != launcher { for _, g := range names { if g == *game { exists = true } } } else if _, ok := games[launcher]; ok { exists = true } if *scheduler { if exists { gs.Start(*game) } else { log.Fatal("Game doesn't exist: ", *game) wg.Done() } } setupHubEventHandlers() setupHubMessageHandlers(games, names) setupHTTPHandlers(games) go func() { err := http.ListenAndServe(*addr, nil) if err != nil { log.Fatal("ListenAndServe: ", err) } wg.Done() }() wg.Wait() }
func setupSchedulerCallbacks() { gs.OnStart(func(name string) { hub.Send(hub.MessageOut{ From: gameClient, To: hub.Broadcast, Action: actionRedirect, Data: name, }) }) gs.OnStop(func(name string, current string) { // If no new game has started if name == current { if name != launcher { gs.Start(launcher) } else { gs.Quit() wg.Done() } } }) }
func setupHubMessageHandlers(games map[string]gp.Game, names []string) { hub.AddMessageHandler(actionGetIP, func(m hub.MessageIn) { host, port, err := net.SplitHostPort(*addr) if err != nil { log.Println("get ip:", err) return } if host == "" || host == "localhost" { host, err = externalIP() if err != nil { log.Println("get ip:", err) return } } displayAddr := net.JoinHostPort(host, port) if port == "80" { displayAddr = host } hub.Send(hub.MessageOut{ To: m.From, Action: actionGetIP, Data: displayAddr, }) }) hub.AddMessageHandler(actionList, func(m hub.MessageIn) { hub.Send(hub.MessageOut{ To: m.From, Action: actionList, Data: names, }) }) hub.AddMessageHandler(actionStart, func(m hub.MessageIn) { var data string err := json.Unmarshal(m.Data, &data) if err != nil { return } gs.Start(data) }) hub.AddMessageHandler(actionDescription, func(m hub.MessageIn) { var data string err := json.Unmarshal(m.Data, &data) if err != nil { return } var description string if game, ok := games[data]; ok { description = game.Description } hub.Send(hub.MessageOut{ To: m.From, Action: actionDescription, Data: description, }) }) hub.AddMessageHandler(actionPlayers, func(m hub.MessageIn) { var data string err := json.Unmarshal(m.Data, &data) if err != nil { return } var players int if game, ok := games[data]; ok { players = game.Players } hub.Send(hub.MessageOut{ To: m.From, Action: actionPlayers, Data: players, }) }) }