Ejemplo n.º 1
0
func main() {
	err := data.OpenDBSession(os.Getenv("MONGO_URL"))
	if err != nil {
		log.Fatal(err)
	}

	err = data.MakeIndexes()
	if err != nil {
		log.Fatal(err)
	}

	hub := hub.New(repo.New())

	gs := glue.NewServer()
	gs.OnNewSocket(hub.HandleSocket)
	http.Handle("/glue/", gs)

	http.Handle("/", ui.NewServer())

	log.Printf("Listening on %s", os.Getenv("ADDR"))
	err = http.ListenAndServe(os.Getenv("ADDR"), nil)
	if err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 2
0
func main() {
	fEnvFile := flag.String("env-file", "", "path to environment file")
	flag.Parse()

	if *fEnvFile != "" {
		err := LoadEnvFile(*fEnvFile)
		if err != nil {
			log.Fatal(err)
		}
	}

	err := data.OpenSession("mongodb://127.0.0.1:27017/tonesa")
	if err != nil {
		log.Fatal(err)
	}
	err = data.MakeIndexes()
	if err != nil {
		log.Fatal(err)
	}

	err = data.InitBucket(os.Getenv("S3_BUCKET_NAME"))
	if err != nil {
		log.Fatal(err)
	}

	err = hub.InitHub(os.Getenv("REDIS_URL"))
	if err != nil {
		log.Fatal(err)
	}

	glueSrv := glue.NewServer(glue.Options{
		HTTPSocketType: glue.HTTPSocketTypeNone,
	})
	glueSrv.OnNewSocket(hub.HandleSocket)

	http.Handle("/", ui.Router)
	http.Handle("/api/", http.StripPrefix("/api", api.Router))
	http.Handle("/assets/", http.StripPrefix("/assets", ui.AssetsFS))
	http.Handle("/glue/", glueSrv)

	port := os.Getenv("PORT")
	log.Printf("Listening on :%s", port)
	err = http.ListenAndServe(":"+port, nil)
	if err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 3
0
func main() {
	// Set the http file server.
	http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("public"))))
	http.Handle("/dist/", http.StripPrefix("/dist/", http.FileServer(http.Dir("../../client/dist"))))

	// Create a new glue server.
	server := glue.NewServer(glue.Options{
		HTTPListenAddress: ":8080",
	})

	// Release the glue server on defer.
	// This will block new incoming connections
	// and close all current active sockets.
	defer server.Release()

	// Set the glue event function to handle new incoming socket connections.
	server.OnNewSocket(onNewSocket)

	// Run the glue server.
	err := server.Run()
	if err != nil {
		log.Fatalf("Glue Run: %v", err)
	}
}
Ejemplo n.º 4
0
// Init initializes the BitMonster runtime and connects to the database.
func Init() error {
	// Load the settings from the environment variables.
	err := settings.LoadFromENV()
	if err != nil {
		return err
	}

	// Parse the flags.
	var paramSettingsPath string
	flag.StringVar(&paramSettingsPath, "s", paramSettingsPath, "load a bitmonster settings file.")
	flag.Parse()

	// Load the settings file if a path is passed.
	if len(paramSettingsPath) > 0 {
		err = settings.Load(paramSettingsPath)
		if err != nil {
			return err
		}
	}

	// Prepare the settings.
	if err = settings.Prepare(); err != nil {
		return err
	}

	// Catch interrupt signals.
	if settings.Settings.AutoCatchInterrupts {
		go func() {
			// Wait for the signal.
			sigchan := make(chan os.Signal, 10)
			signal.Notify(sigchan, os.Interrupt, os.Kill, syscall.SIGTERM, syscall.SIGKILL)
			<-sigchan

			log.L.Info("Exiting...")

			// First cleanup
			release()

			// Exit the application
			os.Exit(InterruptExitCode)
		}()
	}

	// Connect to the database.
	if err = db.Connect(); err != nil {
		return err
	}

	// Prepare to the database.
	if err = db.Prepare(); err != nil {
		return err
	}

	// Create the glue options.
	glueOpts := glue.Options{
		HTTPListenAddress: settings.Settings.ListenAddress,
		HTTPHandleURL:     socketHandleURL,
		CheckOrigin:       CheckOrigin, // Set to the custom implementation.
	}

	// Enable the Cross-Origin Resource Sharing (CORS) mechanism
	// if additional origins are set.
	if len(settings.Settings.AllowOrigin) > 0 {
		glueOpts.EnableCORS = true
	}

	// Set the socket type.
	if settings.Settings.SocketType == settings.SocketTypeTCP {
		glueOpts.HTTPSocketType = glue.HTTPSocketTypeTCP
	} else if settings.Settings.SocketType == settings.SocketTypeUnix {
		glueOpts.HTTPSocketType = glue.HTTPSocketTypeUnix
	} else {
		return fmt.Errorf("settings: invalid socket type: %v", settings.Settings.SocketType)
	}

	// Create the glue server.
	server = glue.NewServer(glueOpts)

	// Set the event function to handle new incoming socket connections.
	server.OnNewSocket(onNewSocket)

	// Trigger the init event.
	emitter.Emit(emitterOnInit)

	return nil
}
Ejemplo n.º 5
0
func main() {

	var err error
	//parse command line arguments
	fEnvFile := flag.String("env-file", "", "path to environment file")
	flag.Parse()

	if *fEnvFile != "" {
		err = LoadEnvFile(*fEnvFile)
		if err != nil {
			log.Fatal(err)
		}
	}

	//try connecting to S3
	log.Println("Initializing S3...")
	err = data.InitBucket(os.Getenv("S3_BUCKET_NAME"))
	if err != nil {
		log.Fatal(err)
	}

	maxAttempts := 20
	//try connecting to mongodb with exponential back-off
	for attempts := 1; attempts <= maxAttempts; attempts++ {
		log.Println(fmt.Sprintf("Connecting to mongodb (%d/%d)...", attempts, maxAttempts))
		err = data.OpenSession(os.Getenv("MONGO_URL"))
		if err == nil {
			break
		}
		log.Println(err.Error() + ", sleeping...")
		time.Sleep(time.Duration(attempts) * time.Second)
	}
	if err != nil {
		log.Fatal(err)
	}

	//try connecting to redis with exponential back-off
	for attempts := 1; attempts <= maxAttempts; attempts++ {
		log.Println(fmt.Sprintf("Connecting to redis (%d/%d)...", attempts, maxAttempts))
		err = hub.Connect(os.Getenv("REDIS_URL"))
		if err == nil {
			break
		}
		log.Println(err.Error() + ", sleeping...")
		time.Sleep(time.Duration(attempts) * time.Second)
	}
	if err != nil {
		log.Fatal(err)
	}
	//init the Hub
	hub.InitHub()

	glueSrv := glue.NewServer(glue.Options{
		HTTPSocketType: glue.HTTPSocketTypeNone,
	})
	glueSrv.OnNewSocket(hub.HandleSocket)

	http.Handle("/", ui.Router)
	http.Handle("/api/", http.StripPrefix("/api", api.Router))
	http.Handle("/assets/", http.StripPrefix("/assets", ui.AssetsFS))
	http.Handle("/glue/", glueSrv)

	port := os.Getenv("PORT")
	//if PORT is blank, use 80 as default
	if port == "" {
		port = "80"
	}

	log.Printf("Listening on :%s", port)
	err = http.ListenAndServe("0.0.0.0:"+port, nil)
	if err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 6
0
func main() {
	// Command line variables
	var debug bool
	var daemon bool
	var bindAddress string
	var listenPort string
	var maxPlayers int

	flag.BoolVar(&debug, "debug", false, "run server in debug mode")
	flag.BoolVar(&daemon, "daemon", false, "run server in daemon mode (no console prompt)")
	flag.StringVar(&bindAddress, "bindAddress", "0.0.0.0", "address to bind to")
	flag.StringVar(&listenPort, "listenPort", "8080", "port to serve client on")
	flag.IntVar(&maxPlayers, "maxPlayers", 4, "max number of players on server simultaneously")
	flag.Parse()

	// Find executable location
	osextDir, err := osext.ExecutableFolder()
	if err != nil {
		log15.Error("Finding executable location", "error", err)
	}

	// Configure GameClient distributor
	http.Handle("/", http.FileServer(http.Dir(osextDir+"/client")))

	// Configure webtron server
	webtronServer := server.New(debug, maxPlayers)
	defer webtronServer.Shutdown()

	// Configure Glue (websocket wrapper) bridge
	glueServer := glue.NewServer(glue.Options{
		HTTPSocketType:    glue.HTTPSocketTypeNone,
		HTTPListenAddress: ":" + listenPort,
		HTTPHandleURL:     "/",
	})
	defer glueServer.Release()
	glueServer.OnNewSocket(webtronServer.ConnectPlayer)
	http.HandleFunc("/ws", glueServer.ServeHTTP)

	if daemon {
		listenAndServe(bindAddress, listenPort)

	} else {
		// Listen for gameclient/websocket requests on http(s)
		go listenAndServe(bindAddress, listenPort)

		// Command line input
		reader := bufio.NewReader(os.Stdin)
	input_loop:
		for {
			fmt.Print("console@webtron:~$ ")
			input, _ := reader.ReadString('\n')
			input = strings.Trim(input, "\n")
			switch input {
			case "":

			case "help":
				fmt.Println(
					"Available commands:\n" +
						"help, exit")

			case "exit", "quit":
				break input_loop

			default:
				fmt.Println("Unknown command: " + input)
			}
		}
	}
}