Exemplo n.º 1
0
Arquivo: main.go Projeto: pressly/qmd
func main() {
	flags.Parse(os.Args[1:])

	// Override config file by the CONFIG env var, if specified.
	if os.Getenv("CONFIG") != "" {
		*confFile = os.Getenv("CONFIG")
	}

	// Read Config.
	conf, err := config.New(*confFile)
	if err != nil {
		log.Fatal(err)
	}

	// Run QMD.
	app, err := qmd.New(conf)
	if err != nil {
		log.Fatal(err)
	}
	go app.WatchScripts()
	go app.StartWorkers()
	go app.ListenQueue()

	graceful.AddSignal(syscall.SIGINT, syscall.SIGTERM)
	graceful.PreHook(app.Close)

	// Start the API server.
	log.Printf("Starting QMD API at %s\n", conf.Bind)
	err = graceful.ListenAndServe(conf.Bind, rest.Routes(app))
	if err != nil {
		log.Fatal(err)
	}
	graceful.Wait()
}
Exemplo n.º 2
0
func main() {
	var err error
	flags.Parse(os.Args[1:])

	conf, err := server.NewConfigFromFile(*confFile, os.Getenv("CONFIG"))
	if err != nil {
		log.Fatal(err)
	}

	srv := server.New(conf)
	if err := srv.Configure(); err != nil {
		log.Fatal(err)
	}

	lg.Infof("** Imgry Server v%s at %s **", imgry.VERSION, srv.Config.Bind)
	lg.Infof("** Engine: %s", srv.ImageEngine.Version())

	graceful.AddSignal(syscall.SIGINT, syscall.SIGTERM)
	graceful.Timeout(30 * time.Second)
	graceful.PreHook(srv.Close)
	graceful.PostHook(srv.Shutdown)

	err = graceful.ListenAndServe(srv.Config.Bind, srv.NewRouter())
	if err != nil {
		lg.Fatal(err.Error())
	}
	graceful.Wait()
}
Exemplo n.º 3
0
func main() {
	var err error
	flags.Parse(os.Args[1:])

	conf, err := server.NewConfigFromFile(*confFile, os.Getenv("CONFIG"))
	if err != nil {
		log.Fatal(err)
	}

	srv := server.New(conf)

	graceful.AddSignal(syscall.SIGINT, syscall.SIGTERM)
	graceful.PreHook(func() { srv.Close() })

	if err := srv.Configure(); err != nil {
		log.Fatal(err)
	}

	lg.Infof("** Imgry Server v%s at %s **\n", imgry.VERSION, srv.Config.Server.Addr)
	lg.Infof("** Engine: %s", imagick.Engine{}.Version())

	err = graceful.ListenAndServe(srv.Config.Server.Addr, srv.NewRouter())
	if err != nil {
		lg.Fatal(err.Error())
	}
	graceful.Wait()
}
Exemplo n.º 4
0
func main() {
	flag.StringVar(&Config.bind, "bind", "127.0.0.1:8080",
		"host to bind to (default: 127.0.0.1:8080)")
	flag.StringVar(&Config.filesDir, "filespath", "files/",
		"path to files directory")
	flag.StringVar(&Config.metaDir, "metapath", "meta/",
		"path to metadata directory")
	flag.BoolVar(&Config.noLogs, "nologs", false,
		"remove stdout output for each request")
	flag.BoolVar(&Config.allowHotlink, "allowhotlink", false,
		"Allow hotlinking of files")
	flag.StringVar(&Config.siteName, "sitename", "linx",
		"name of the site")
	flag.StringVar(&Config.siteURL, "siteurl", "http://"+Config.bind+"/",
		"site base url (including trailing slash)")
	flag.Int64Var(&Config.maxSize, "maxsize", 4*1024*1024*1024,
		"maximum upload file size in bytes (default 4GB)")
	flag.StringVar(&Config.certFile, "certfile", "",
		"path to ssl certificate (for https)")
	flag.StringVar(&Config.keyFile, "keyfile", "",
		"path to ssl key (for https)")
	flag.BoolVar(&Config.fastcgi, "fastcgi", false,
		"serve through fastcgi")
	flag.BoolVar(&Config.remoteUploads, "remoteuploads", false,
		"enable remote uploads")
	flag.StringVar(&Config.contentSecurityPolicy, "contentsecuritypolicy",
		"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; referrer none;",
		"value of default Content-Security-Policy header")
	flag.StringVar(&Config.fileContentSecurityPolicy, "filecontentsecuritypolicy",
		"default-src 'none'; img-src 'self'; object-src 'self'; media-src 'self'; sandbox; referrer none;",
		"value of Content-Security-Policy header for file access")
	flag.StringVar(&Config.xFrameOptions, "xframeoptions", "SAMEORIGIN",
		"value of X-Frame-Options header")
	flag.Parse()

	mux := setup()

	if Config.fastcgi {
		listener, err := net.Listen("tcp", Config.bind)
		if err != nil {
			log.Fatal("Could not bind: ", err)
		}

		log.Printf("Serving over fastcgi, bound on %s, using siteurl %s", Config.bind, Config.siteURL)
		fcgi.Serve(listener, mux)
	} else if Config.certFile != "" {
		log.Printf("Serving over https, bound on %s, using siteurl %s", Config.bind, Config.siteURL)
		err := graceful.ListenAndServeTLS(Config.bind, Config.certFile, Config.keyFile, mux)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		log.Printf("Serving over http, bound on %s, using siteurl %s", Config.bind, Config.siteURL)
		err := graceful.ListenAndServe(Config.bind, mux)
		if err != nil {
			log.Fatal(err)
		}
	}
}
Exemplo n.º 5
0
// Serve starts the server
func (a *App) Serve() {
	// External endpoints
	external := web.New()
	external.Use(server.StripTrailingSlashMiddleware())
	external.Use(server.HeadersMiddleware())
	external.Post("/", a.requestHandler.HandlerAuth)
	externalPortString := fmt.Sprintf(":%d", *a.config.ExternalPort)
	log.Println("Starting external server on", externalPortString)
	go func() {
		var err error
		if a.config.TLS.CertificateFile != "" && a.config.TLS.PrivateKeyFile != "" {
			err = graceful.ListenAndServeTLS(
				externalPortString,
				a.config.TLS.CertificateFile,
				a.config.TLS.PrivateKeyFile,
				external,
			)
		} else {
			err = graceful.ListenAndServe(externalPortString, external)
		}

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

	// Internal endpoints
	internal := web.New()
	internal.Use(server.StripTrailingSlashMiddleware())
	internal.Use(server.HeadersMiddleware())
	internal.Post("/send", a.requestHandler.HandlerSend)
	internal.Post("/receive", a.requestHandler.HandlerReceive)
	internal.Post("/allow_access", a.requestHandler.HandlerAllowAccess)
	internal.Post("/remove_access", a.requestHandler.HandlerRemoveAccess)
	internalPortString := fmt.Sprintf(":%d", *a.config.InternalPort)
	log.Println("Starting internal server on", internalPortString)
	err := graceful.ListenAndServe(internalPortString, internal)
	if err != nil {
		log.Fatal(err)
	}
}
Exemplo n.º 6
0
//Server ...
func Server(port int) {
	log.Info("Server start. Please visit http://localhost:" + strconv.Itoa(port))
	log.Infoln("Press ctrl-c to stop")
	http.Handle("/dashboard/blog/new", http.HandlerFunc(newBlogHandle))
	http.Handle("/dashboard/generate", http.HandlerFunc(generateHandle))
	http.Handle("/dashboard/deploy", http.HandlerFunc(deployHandle))
	http.Handle("/dashboard/", http.StripPrefix("/dashboard/", http.FileServer(http.Dir(blog.ThemeDir+"/dashboard"))))
	var config = blog.GetConfig()
	http.Handle("/", http.FileServer(http.Dir(config.PublicDir)))
	fmt.Println(blog.ThemeDir + "/dashboard")
	if err := graceful.ListenAndServe(":"+strconv.Itoa(port), nil); err != nil {
		log.Errorln("[Fail] fail to start server: ", err)
	}
}
func main() {
	// sets the maximum number of CPUs that can be executing simultaneously
	runtime.GOMAXPROCS(runtime.NumCPU())

	// override defaults via env vars
	if os.Getenv("ES_HOST") != "" {
		esHost = os.Getenv("ES_HOST")
	}
	if os.Getenv("ES_PORT") != "" {
		esPort = os.Getenv("ES_PORT")
	}
	if os.Getenv("REDIS_HOST") != "" {
		redisHost = os.Getenv("REDIS_HOST")
	}
	if os.Getenv("REDIS_PORT") != "" {
		redisPort = os.Getenv("REDIS_PORT")
	}
	if os.Getenv("PUBLIC_DIR") != "" {
		publicDir = os.Getenv("PUBLIC_DIR")
	}

	// log endpoints
	log.Infof("Redis endpoint set to %s:%s", redisHost, redisPort)
	log.Infof("Elasticsearch endpoint set to %s:%s", esHost, esPort)

	// register available tiling types
	tile.Register("heatmap", elastic.NewHeatmapTile(esHost, esPort))
	tile.Register("topic_count", elastic.NewTopCountTile(esHost, esPort))
	// register available meta data types
	meta.Register("default", elastic.NewDefaultMeta(esHost, esPort))
	// register available store types
	store.Register("redis", redis.NewConnection(redisHost, redisPort))

	// create server
	app := api.New(publicDir)

	// catch kill signals for graceful shutdown
	graceful.AddSignal(syscall.SIGINT, syscall.SIGTERM)
	// start server
	log.Infof("Prism server listening on port %s", port)
	err := graceful.ListenAndServe(":"+port, app)
	if err != nil {
		log.Error(err)
	}
	// wait until server gracefully exits
	graceful.Wait()
}
Exemplo n.º 8
0
// Serves the HTTP Application
func Serve(a *sir.ApplicationContext) {
	// Create new Web Client
	r := web.New()

	// Register Routes
	r.Get("/", sir.ApplicationHandler{a, statsHandler})
	r.Post("/", sir.ApplicationHandler{a, register.RegisterHandler})
	r.Get("/:instance_id", sir.ApplicationHandler{a, register.DetailsHandler})
	r.Delete("/:instance_id", sir.ApplicationHandler{a, unregister.UnRegisterHandler})

	// Setup Middleware
	r.Use(JSONContentType)
	r.Use(middleware.Logger)

	// Serve the Application
	graceful.ListenAndServe(":8000", r)
}
Exemplo n.º 9
0
func (api *CassabonAPI) run() {
	// Initialize API server
	api.server = web.New()

	// Define routes
	api.server.Get("/", api.rootHandler)
	api.server.Get("/paths", api.getPathHandler)
	api.server.Get("/metrics", api.getMetricHandler)
	api.server.Get("/healthcheck", api.healthHandler)
	api.server.Delete("/paths", api.deletePathHandler)
	api.server.Delete("/metrics", api.deleteMetricHandler)
	api.server.NotFound(api.notFoundHandler)

	api.server.Use(requestLogger)

	config.G.Log.System.LogInfo("API initialized, serving!")
	graceful.ListenAndServe(api.hostPort, api.server)
}
Exemplo n.º 10
0
// Application Entrypoint
func main() {
	// Message Hub
	hub := socket.NewHub()
	go hub.Run()

	// WS Service
	ws := socket.NewWSService(hub)

	// Redis Subscription
	s := pubsub.NewSubscription(
		hub,
		viper.GetString("redis_host"),
		viper.GetString("redis_port"))
	go s.Consume()

	c := web.New()

	// Middlewares
	c.Use(middleware.SetupEnv)
	c.Use(middleware.HMACVerification)
	c.Use(middleware.CustomValidators)
	c.Use(middleware.RedisClient)

	// WS Connection Handler
	c.Get("/", ws.Handler)

	// Event REST endpoints
	c.Post("/events/play", rest.PlayCreateHandler)
	c.Post("/events/end", rest.EndCreateHandler)
	c.Post("/events/pause", rest.PauseCreateHandler)
	c.Post("/events/resume", rest.ResumeCreateHandler)

	// Updates to Mute / Volume States
	c.Put("/volume", rest.VolumeUpdateHandler)
	c.Put("/mute", rest.MuteUpdateHandler)

	// Get the next track from the playlist
	c.Get("/playlist/next", rest.GetNextTrackHandler)

	// Start Serving Web Application
	log.Infof("Starting Server on :%s", viper.GetString("port"))
	graceful.ListenAndServe(fmt.Sprintf(":%s", viper.GetString("port")), c)
}
Exemplo n.º 11
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	// Parse the flags and store them as a conf struct
	flag.Parse()
	conf := skeletor.Conf{
		Prod:    *prod,
		Version: version,
	}
	skeletor.SaveConf(&conf)

	// Start the web server
	graceful.AddSignal(syscall.SIGINT, syscall.SIGTERM)
	app := api.New()
	log.Println("Skeletor server listening on", *bind)
	err := graceful.ListenAndServe(*bind, app)
	if err != nil {
		log.Fatal(err)
	}

	graceful.Wait()
}
Exemplo n.º 12
0
func main() {
	flag.StringVar(&Config.bind, "bind", "127.0.0.1:8080",
		"host to bind to (default: 127.0.0.1:8080)")
	flag.StringVar(&Config.filesDir, "filespath", "files/",
		"path to files directory")
	flag.StringVar(&Config.metaDir, "metapath", "meta/",
		"path to metadata directory")
	flag.BoolVar(&Config.noLogs, "nologs", false,
		"remove stdout output for each request")
	flag.BoolVar(&Config.allowHotlink, "allowhotlink", false,
		"Allow hotlinking of files")
	flag.StringVar(&Config.siteName, "sitename", "",
		"name of the site")
	flag.StringVar(&Config.siteURL, "siteurl", "",
		"site base url (including trailing slash)")
	flag.Int64Var(&Config.maxSize, "maxsize", 4*1024*1024*1024,
		"maximum upload file size in bytes (default 4GB)")
	flag.Uint64Var(&Config.maxExpiry, "maxexpiry", 0,
		"maximum expiration time in seconds (default is 0, which is no expiry)")
	flag.StringVar(&Config.certFile, "certfile", "",
		"path to ssl certificate (for https)")
	flag.StringVar(&Config.keyFile, "keyfile", "",
		"path to ssl key (for https)")
	flag.BoolVar(&Config.realIp, "realip", false,
		"use X-Real-IP/X-Forwarded-For headers as original host")
	flag.BoolVar(&Config.fastcgi, "fastcgi", false,
		"serve through fastcgi")
	flag.BoolVar(&Config.remoteUploads, "remoteuploads", false,
		"enable remote uploads")
	flag.StringVar(&Config.authFile, "authfile", "",
		"path to a file containing newline-separated scrypted auth keys")
	flag.StringVar(&Config.remoteAuthFile, "remoteauthfile", "",
		"path to a file containing newline-separated scrypted auth keys for remote uploads")
	flag.StringVar(&Config.contentSecurityPolicy, "contentsecuritypolicy",
		"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; frame-ancestors 'self'; referrer origin;",
		"value of default Content-Security-Policy header")
	flag.StringVar(&Config.fileContentSecurityPolicy, "filecontentsecuritypolicy",
		"default-src 'none'; img-src 'self'; object-src 'self'; media-src 'self'; style-src 'self' 'unsafe-inline'; frame-ancestors 'self'; referrer origin;",
		"value of Content-Security-Policy header for file access")
	flag.StringVar(&Config.xFrameOptions, "xframeoptions", "SAMEORIGIN",
		"value of X-Frame-Options header")
	flag.Var(&Config.addHeaders, "addheader",
		"Add an arbitrary header to the response. This option can be used multiple times.")
	flag.StringVar(&Config.googleShorterAPIKey, "googleapikey", "",
		"API Key for Google's URL Shortener.")

	iniflags.Parse()

	mux := setup()

	if Config.fastcgi {
		listener, err := net.Listen("tcp", Config.bind)
		if err != nil {
			log.Fatal("Could not bind: ", err)
		}

		log.Printf("Serving over fastcgi, bound on %s", Config.bind)
		fcgi.Serve(listener, mux)
	} else if Config.certFile != "" {
		log.Printf("Serving over https, bound on %s", Config.bind)
		err := graceful.ListenAndServeTLS(Config.bind, Config.certFile, Config.keyFile, mux)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		log.Printf("Serving over http, bound on %s", Config.bind)
		err := graceful.ListenAndServe(Config.bind, mux)
		if err != nil {
			log.Fatal(err)
		}
	}
}