Ejemplo n.º 1
0
func main() {
	c, err := myrpc.Dial("tcp", checkEnv("VEIL_LISTENER"))
	check(err)
	h := handlers.New(&handlers.H{C: c})
	r := mux.NewRouter()
	r.HandleFunc("/api/version", h.Version).Methods("GET")
	r.HandleFunc("/api/payloads", h.Payloads).Methods("GET")
	r.HandleFunc("/api/options", h.PayloadOptions).Methods("GET")
	r.HandleFunc("/api/generate", h.Generate).Methods("POST")
	n := negroni.New()
	n.Use(negroni.NewLogger())
	n.Use(negroni.NewRecovery())
	n.Use(negroni.NewStatic(http.Dir(checkEnv("VEIL_OUTPUT_DIR"))))
	n.Use(auth.Basic(checkEnv("ADMIN_USER"), checkEnv("ADMIN_PASS")))
	n.Use(negroni.NewStatic(http.Dir("public")))
	n.Use(negroni.HandlerFunc(func(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
		if req.Method != "POST" {
			next(w, req)
			return
		}
		if !strings.Contains(req.Header.Get("content-type"), "application/json") {
			h.JSON400(w, errors.New("Content-Type must be application/json"))
			return
		}
		next(w, req)
	}))
	n.UseHandler(r)
	n.Run(checkEnv("SERVER_LISTENER"))
}
Ejemplo n.º 2
0
func main() {

	router := mux.NewRouter()
	router.HandleFunc(xmlEndpoint+"/alerts", func(res http.ResponseWriter, req *http.Request) {
		res.Header().Set("Access-Control-Allow-Origin", "*")
	}).Methods("OPTIONS")

	//router.HandleFunc(xmlEndpoint+"/alerts", alertPost).Methods("POST")
	//router.HandleFunc(xmlEndpoint+"/alerts", alertsGet).Methods("GET")
	router.HandleFunc(xmlEndpoint+"/alerts/{id}", alertGet).Methods("GET")
	router.HandleFunc(jsonEndpoint+"/alerts", alertPostJson).Methods("POST")
	router.HandleFunc(jsonEndpoint+"/alerts", alertsGetJson).Methods("GET")
	router.HandleFunc(jsonEndpoint+"/alerts/{id}", alertGetJson).Methods("GET")
	// router.HandleFunc("/alerts/{id}", alertPost).Methods("POST")

	router.HandleFunc(xmlEndpoint+"/feed", getAtomFeed)

	//router.HandleFunc("/mdc", DrgHandler).Methods("GET")
	// router.HandleFunc("/", HomeHandler)

	n := negroni.New(negroni.NewRecovery(), NewLogger(), negroni.NewStatic(http.Dir("dist")))

	n.UseHandler(router)
	n.Run(qcapListen)
}
Ejemplo n.º 3
0
func newServer() *http.Server {
	n := negroni.New()

	// Middlewares
	if Settings["environments"].GetBool("log") {
		n.Use(negroni.NewLogger())
	}

	n.UseFunc(recovery())
	n.Use(negroni.NewStatic(http.Dir("./public")))

	// Setup routes
	router := pat.New()
	router.Get("/api/v1/:env/driver/:ID", http.HandlerFunc(getDriverLocation))
	//router.Post("/api/v1/<resource>", http.HandlerFunc(/*handle func*/))

	// Add alive endpoint
	// router.Get("/alive", http.HandlerFunc(alive))
	// Add the router action
	n.UseHandler(router)
	Server := &http.Server{
		Addr:           ":" + Settings["environments"].GetString("server.port"),
		Handler:        n,
		ReadTimeout:    5 * time.Second,
		WriteTimeout:   5 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	return Server
}
Ejemplo n.º 4
0
Archivo: app.go Proyecto: ramigg/ok-go
// This function is called from main.go and from the tests
// to create a new application.
func NewApp(root string) *App {

	CheckEnv()

	// Use negroni for middleware
	ne := negroni.New()

	// Use gorilla/mux for routing
	ro := mux.NewRouter()

	// Use Render for template. Pass in path to templates folder
	// as well as asset helper functions.
	re := render.New(render.Options{
		Directory:  filepath.Join(root, "templates"),
		Layout:     "layouts/layout",
		Extensions: []string{".html"},
		Funcs:      []template.FuncMap{AssetHelpers(root)},
	})

	// Establish connection to DB as specificed in database.go
	db := NewDB()

	// Add middleware to the stack
	ne.Use(negroni.NewRecovery())
	ne.Use(negroni.NewLogger())
	ne.Use(NewAssetHeaders())
	ne.Use(negroni.NewStatic(http.Dir("public")))
	ne.UseHandler(ro)

	// Return a new App struct with all these things.
	return &App{ne, ro, re, db}
}
Ejemplo n.º 5
0
func serverRun(cmd *cobra.Command, args []string) {
	// MongoDB setup
	CreateUniqueIndexes()
	// Web Server Setup
	CreateStore()
	webRouter := CreateWebRouter()
	teamRouter := CreateTeamRouter()

	app := negroni.New()
	webRouter.PathPrefix("/").Handler(negroni.New(
		negroni.HandlerFunc(RequireLogin),
		negroni.Wrap(teamRouter),
	))
	app.Use(negroni.NewLogger())
	app.Use(negroni.NewStatic(http.Dir("static")))
	app.Use(negroni.HandlerFunc(CheckSessionID))

	app.UseHandler(webRouter)

	l := log.New(os.Stdout, "[negroni] ", 0)
	http_port := viper.GetString("server.http_port")
	https_port := viper.GetString("server.https_port")
	cert := viper.GetString("server.cert")
	key := viper.GetString("server.key")

	l.Printf("Server running at: https://%s:%s", viper.GetString("server.ip"), https_port)

	go http.ListenAndServe(":"+http_port, http.HandlerFunc(redir))

	l.Fatal(http.ListenAndServeTLS(":"+https_port, cert, key, app))
}
Ejemplo n.º 6
0
func main() {
	cfg.MustLoad()
	listeningAddr := ":" + cfg.Server.Port

	router := mux.NewRouter().PathPrefix(cfg.Server.API.Prefix).Subrouter()

	db, err := pg.NewSession(cfg.DB.ConnectionURL())
	if err != nil {
		log.Fatalf("Unable to connect to database: %s", err)
	}

	vars := map[string]interface{}{"db": db}

	err = ctx.Init(router, cfg.Server.API.PrivKey, cfg.Server.API.PubKey, vars)
	if err != nil {
		log.Fatalf("Unable to configure API: %s", err)
	}

	server := negroni.New(
		negroni.NewRecovery(),
		negroni.HandlerFunc(WebLogger),
		negroni.NewStatic(http.Dir(cfg.Server.Frontend.Path)),
	)
	server.UseHandler(router)

	log.Infof("Listening on address: %s", listeningAddr)
	log.Fatal(http.ListenAndServe(listeningAddr, server))
}
Ejemplo n.º 7
0
func StartServer() {
	rest.P()
	// Log to file
	f, err := os.OpenFile("logs/arkeogis.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalf("Error opening log file: %v", err)
	}
	defer f.Close()
	log.SetOutput(f)
	// Configure Negroni and start server
	Negroni := negroni.New(
		negroni.NewRecovery(),
		negroni.HandlerFunc(crossDomainMiddleware),
		NewLogger(),
		negroni.NewStatic(http.Dir(config.WebPath)),
	)
	Negroni.UseHandler(routes.MuxRouter)
	/* DEBUG SENDING MAIL
	fmt.Println("SENDING MAIL")
	errrr := mail.Send([]string{"*****@*****.**"}, "pouet", "poeut", "fr")
	if errrr != nil {
		log.Println(errors.ErrorStack(errrr))
	}
	fmt.Println("starting web server...")
	*/
	Negroni.Run(":" + strconv.Itoa(config.Main.Server.Port))
}
Ejemplo n.º 8
0
func configureHttpAndListen(config *AppConfig, db gorm.DB) {
	// register routes
	r := render.New(render.Options{})
	h := DBHandler{db: &db, r: r}

	router := mux.NewRouter()

	router.HandleFunc("/api/schedules", h.schedulesIndexHandler).Methods("GET")
	router.HandleFunc("/api/schedules", h.scheduleCreateHandler).Methods("POST")
	router.HandleFunc("/api/schedules/{id:[0-9]+}", h.scheduleShowHandler).Methods("GET")
	router.HandleFunc("/api/schedules/{id:[0-9]+}", h.scheduleUpdateHandler).Methods("PUT", "PATCH")
	router.HandleFunc("/api/schedules/{id:[0-9]+}", h.scheduleDeleteHandler).Methods("DELETE")

	router.HandleFunc("/api/cards", h.cardsIndexHandler).Methods("GET")
	router.HandleFunc("/api/cards", h.cardCreateHandler).Methods("POST")
	router.HandleFunc("/api/cards/{id:[0-9]+}", h.cardShowHandler).Methods("GET")
	router.HandleFunc("/api/cards/{id:[0-9]+}", h.cardUpdateHandler).Methods("PUT", "PATCH")
	router.HandleFunc("/api/cards/{id:[0-9]+}", h.cardDeleteHandler).Methods("DELETE")

	router.HandleFunc("/api/logs", h.logsIndexHandler).Methods("GET")

	n := negroni.New(
		negroni.NewRecovery(),
		negroni.NewStatic(http.Dir(config.AssetPath)),
	)

	n.Use(auth.Basic(config.Authentication.Username, config.Authentication.Password))
	n.UseHandler(router)
	n.Run(":" + config.Port)
}
Ejemplo n.º 9
0
func NewApp() *App {
	db := newDB()

	// Use negroni for middleware
	ne := negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
		negroni.NewStatic(http.Dir("public")),
	)

	// Use gorilla/mux for routing
	ro := mux.NewRouter()

	// Set StrictSlash to allow /things/ to automatically redirect to /things
	ro.StrictSlash(true)

	// Use Render for template. Pass in path to templates folder
	// as well as asset helper functions.
	re := render.New(render.Options{
		Layout:     "layouts/layout",
		Extensions: []string{".html"},
	})

	ne.UseHandler(ro)

	return &App{ne, ro, re, db}
}
Ejemplo n.º 10
0
func main() {
	conf.Parse()

	restrict.ReadCryptoKey("keys/app.rsa")

	router := mux.NewRouter()
	router.HandleFunc("/users", GetUserHandler).Methods("GET")
	router.HandleFunc("/users/login", LoginHandler).Methods("POST")
	router.HandleFunc("/users/register", RegisterHandler).Methods("POST")
	router.HandleFunc("/classes", restrict.R(CreateClassHandler)).Methods("POST")
	router.HandleFunc("/classes", restrict.R(GetClassesHandler)).Methods("GET")
	router.HandleFunc("/classes/{class_id}/workshops", restrict.R(CreateWorkshopHandler)).Methods("POST")
	router.HandleFunc("/classes/{class_id}/workshops/{workshop_id}/pages", restrict.R(CreateWorkshopPageHandler)).Methods("POST")
	router.HandleFunc("/classes/{class_id}/workshops/{workshop_id}/pages", restrict.R(GetWorkshopPagesHandler)).Methods("GET")
	router.HandleFunc("/classes/{class_id}/workshops/{workshop_id}/pages/{page_id}/edit", restrict.R(EditPageHandler)).Methods("POST")
	router.HandleFunc("/classes/{class_id}/workshops/{workshop_id}", restrict.R(GetWorkshopHandler)).Methods("GET")
	router.HandleFunc("/classes/{class_id}/workshops/{workshop_id}", restrict.R(EditWorkshopHandler)).Methods("PUT")
	router.HandleFunc("/classes/{class_id}/workshops/{workshop_id}", restrict.R(DeleteWorkshopHandler)).Methods("DELETE")
	router.HandleFunc("/classes/{class_id}/workshops", restrict.R(GetWorkshopsHandler)).Methods("GET")
	router.HandleFunc("/classes/{class_id}/students", restrict.R(GetStudentHandler)).Methods("GET")
	router.HandleFunc("/classes/{class_id}/image", restrict.R(SetClassImageHandler)).Methods("POST")
	router.HandleFunc("/classes/{class_id}/admin/students", restrict.R(AddUserToClassHandler)).Methods("POST")

	n := negroni.New()
	n.Use(negroni.NewStatic(http.Dir("static")))
	n.Use(negroni.NewLogger())
	n.UseHandler(router)

	models.InitDB(*dbFile)

	http.ListenAndServe("localhost:8080", n)
}
Ejemplo n.º 11
0
func main() {
	settings := evergreen.GetSettingsOrExit()
	if settings.Ui.LogFile != "" {
		evergreen.SetLogger(settings.Ui.LogFile)
	}
	db.SetGlobalSessionProvider(db.SessionFactoryFromConfig(settings))

	home := evergreen.FindEvergreenHome()

	userManager, err := auth.LoadUserManager(settings.AuthConfig)
	if err != nil {
		fmt.Println("Failed to create user manager:", err)
		os.Exit(1)
	}

	cookieStore := sessions.NewCookieStore([]byte(settings.Ui.Secret))

	uis := ui.UIServer{
		nil,             // render
		settings.Ui.Url, // RootURL
		userManager,     // User Manager
		*settings,       // mci settings
		cookieStore,     // cookiestore
		nil,             // plugin panel manager
	}
	router, err := uis.NewRouter()
	if err != nil {
		fmt.Println("Failed to create router:", err)
		os.Exit(1)
	}

	webHome := filepath.Join(home, "public")

	functionOptions := ui.FuncOptions{webHome, settings.Ui.HelpUrl, true, router}

	functions, err := ui.MakeTemplateFuncs(functionOptions, settings.SuperUsers)
	if err != nil {
		fmt.Println("Failed to create template function map:", err)
		os.Exit(1)
	}

	uis.Render = render.New(render.Options{
		Directory:    filepath.Join(home, ui.WebRootPath, ui.Templates),
		DisableCache: !settings.Ui.CacheTemplates,
		Funcs:        functions,
	})
	err = uis.InitPlugins()
	if err != nil {
		fmt.Println("WARNING: Error initializing plugins:", err)
	}

	n := negroni.New()
	n.Use(negroni.NewStatic(http.Dir(webHome)))
	n.Use(ui.NewLogger())
	n.Use(negroni.HandlerFunc(ui.UserMiddleware(userManager)))
	n.UseHandler(router)
	graceful.Run(settings.Ui.HttpListenAddr, requestTimeout, n)
	evergreen.Logger.Logf(slogger.INFO, "UI server cleanly terminated")
}
Ejemplo n.º 12
0
func main() {

	n := negroni.Classic()
	n.Use(negroni.NewStatic(http.Dir(".")))

	// listen on port
	n.Run(":8080")
}
Ejemplo n.º 13
0
func StaticPathFallback(path string) http.Handler {
	return negroni.New(
		negroni.NewStatic(http.Dir(path)),
		negroni.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			r.URL.Path = "/"
			http.FileServer(http.Dir(path)).ServeHTTP(w, r)
		})))
}
Ejemplo n.º 14
0
func (srv *Server) setupNegroni() {
	srv.log.Debug("setting up negroni")
	srv.n = negroni.New()
	srv.n.Use(negroni.NewRecovery())
	srv.n.Use(negronilogrus.NewMiddleware())
	srv.n.Use(negroni.NewStatic(http.Dir("public")))
	srv.n.UseHandler(srv.Router)
}
Ejemplo n.º 15
0
func main() {
	// Load the configuration.
	err := envconfig.Process("elwinar", &configuration)
	if err != nil {
		log.Fatalln("unable to read the configuration from env:", err)
	}

	// Open the database connection.
	database, err = sqlx.Connect("sqlite3", configuration.Database)
	if err != nil {
		log.Fatalln("unable to open the database:", err)
	}

	// Initialize the router.
	router := httprouter.New()

	// Add the front-office handlers.
	router.GET("/", Index)
	router.GET("/read", List)
	router.GET("/article/:slug", View)
	router.GET("/fortune", Fortune)
	router.GET("/sitemap.xml", Sitemap)

	// Add the back-office handlers.
	router.GET("/login", Login)
	router.POST("/login", Authenticate)
	router.GET("/logout", Logout)
	router.GET("/write", Write)
	router.POST("/write", Create)
	router.GET("/article/:slug/edit", Edit)
	router.POST("/article/:slug/edit", Update)
	router.GET("/article/:slug/delete", Delete)
	router.GET("/article/:slug/publish", Publish)
	router.GET("/article/:slug/unpublish", Unpublish)

	// Initialize the server middleware stack.
	stack := negroni.New()
	stack.Use(gzip.Gzip(gzip.DefaultCompression))
	stack.Use(negroni.NewRecovery())
	stack.Use(negroni.NewStatic(http.Dir(configuration.Public)))
	stack.Use(sessions.Sessions("elwinar", cookiestore.New([]byte(configuration.Secret))))
	stack.UseHandler(router)

	// Initialize the HTTP server.
	server := &graceful.Server{
		Timeout: 1 * time.Second,
		Server: &http.Server{
			Addr:    fmt.Sprintf(":%d", configuration.Port),
			Handler: stack,
		},
	}

	// Run the server.
	err = server.ListenAndServe()
	if err != nil {
		log.Fatalln("unable to run the server:", err)
	}
}
Ejemplo n.º 16
0
func main() {
	n := negroni.New(
		negroni.NewRecovery(),
		negroni.HandlerFunc(MyMiddleware),
		negroni.NewLogger(),
		negroni.NewStatic(http.Dir("public")),
	)
	n.Run(":8080")
}
Ejemplo n.º 17
0
func (self *Server) Serve() error {
	self.mux = http.NewServeMux()
	self.router = httprouter.New()

	self.RoutePrefix = strings.TrimSuffix(self.RoutePrefix, `/`)

	// load route handlers
	if err := self.LoadRoutes(); err != nil {
		return err
	}

	staticHandler := negroni.NewStatic(self.MountProxy)

	if self.RoutePrefix != DEFAULT_ROUTE_PREFIX {
		staticHandler.Prefix = self.RoutePrefix
	}

	self.mux.HandleFunc(`/_bindings`, func(w http.ResponseWriter, req *http.Request) {
		if req.URL.Path == `/_bindings` {
			if data, err := json.Marshal(self.Config.Bindings); err == nil {
				w.Header().Set(`Content-Type`, `application/json`)

				if _, err := w.Write(data); err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
			} else {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}
	})

	// add custom http.Handlers to the mux
	for i, handler := range self.Handlers {
		log.Debugf("Setting up custom handler %d for pattern '%s'", i, handler.Pattern)
		self.mux.Handle(handler.Pattern, handler.Handler)
	}

	// add custom http.HandleFuncs to the mux
	for i, handleFunc := range self.HandleFuncs {
		log.Debugf("Setting up custom handler function %d for pattern '%s'", i, handleFunc.Pattern)
		self.mux.HandleFunc(handleFunc.Pattern, handleFunc.HandleFunc)
	}

	// fallback to httprouter (these are the routes defined in the configuration)
	self.mux.Handle(`/`, self.router)

	self.server = negroni.New()
	self.server.Use(negroni.NewRecovery())
	self.server.Use(staticHandler)
	self.server.Use(negroni.Wrap(self.mux))

	self.server.Run(fmt.Sprintf("%s:%d", self.Address, self.Port))
	return nil
}
Ejemplo n.º 18
0
func main() {
	log.Println("Starting...")
	runtime.GOMAXPROCS(runtime.NumCPU())

	r := mux.NewRouter()

	r.HandleFunc("/socket", func(w http.ResponseWriter, req *http.Request) {
		conn, err := upgrader.Upgrade(w, req, nil)
		if err != nil {
			log.Println(err)
			return
		}

		conns = append(conns, conn)
	})

	r.Methods("POST").Path("/switch-mode").HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		var post PostBodySwitchMode
		dec := json.NewDecoder(req.Body)
		err := dec.Decode(&post)

		if err != nil {
			log.Println(err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		switchMode(post.Mode, post.Address)
	})

	n := negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
		negroni.NewStatic(rice.MustFindBox("public").HTTPBox()),
	)
	n.UseHandler(r)
	listen := os.Getenv("LISTEN")
	if listen == "" {
		listen = ":3000"
	}

	lineCh = make(chan string, 32)

	go func() {
		for line := range lineCh {
			for _, conn := range conns {
				err := conn.WriteMessage(websocket.TextMessage, []byte(line))
				if nil != err {
					log.Println(err)
				}
			}
		}
	}()

	n.Run(listen)
}
Ejemplo n.º 19
0
func main() {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	must(err)
	distBase := filepath.Join(dir, "..")

	port := flag.Uint("port", 8080, "port to listen on")
	templateDir := flag.String("templateDir", filepath.Join(distBase, "web", "templates"), "path to html templates")
	storeDir := flag.String("storeDir", filepath.Join(distBase, "db"), "directory for saving persistent data")
	buildsDir := flag.String("buildsDir", filepath.Join(distBase, "builds"), "directory for saving build output")
	assetsDir := flag.String("assetsDir", filepath.Join(distBase, "web", "assets"), "path to static web assets")
	gooseCmd := flag.String("gooseCmd", filepath.Join(distBase, "bin", "goose"), `path to "goose" database migration tool`)
	debugMode := flag.Bool("debugMode", false, "do not parse templates up front. Only for development use")
	flag.Parse()

	bootMsg := ` _    _                 _ _                                 _____ _____
| |  | |               | | |                               /  __ \_   _|
| |  | | ___   ___   __| | |__   ___  _   _ ___  ___ ______| /  \/ | |
| |/\| |/ _ \ / _ \ / _` + "`" + ` | '_ \ / _ \| | | / __|/ _ \______| |     | |
\  /\  / (_) | (_) | (_| | | | | (_) | |_| \__ \  __/      | \__/\_| |_
 \/  \/ \___/ \___/ \__,_|_| |_|\___/ \__,_|___/\___|       \____/\___/
`

	fmt.Println(bootMsg)
	if *debugMode {
		log.Println("Starting in debug mode")
	}

	dbDir := filepath.Join(*storeDir, "sqlite")
	must(os.MkdirAll(dbDir, 0755))

	migrateCmd := exec.Command(*gooseCmd, "up")
	migrateCmd.Dir = filepath.Join(*storeDir, "..")
	must(migrateCmd.Run())

	jobRepo, err := db.NewJobRepository(filepath.Join(dbDir, "store.db"))
	must(err)

	// Only Interrupt handled, as this is available on all major platforms and is the most common way of stopping Woodhouse-CI
	exitChan := make(chan os.Signal)
	signal.Notify(exitChan, os.Interrupt)
	go func(c <-chan os.Signal) {
		log.Printf("Caught signal %s. Closing database connections. Goodbye!\n", <-c)
		must(jobRepo.Close())
		os.Exit(0)
	}(exitChan)

	handler := web.New(&jobs.Service{
		JobRepository:   jobRepo,
		Runner:          runner.NewDockerRunner(vcs.GitCloner{}),
		BuildRepository: builds.NewRepository(*buildsDir),
	}, *templateDir, !*debugMode)

	server := negroni.New(negroni.NewRecovery(), negroni.NewLogger(), negroni.NewStatic(http.Dir(*assetsDir)))
	server.UseHandler(handler)
	server.Run(fmt.Sprintf("0.0.0.0:%d", *port))
}
Ejemplo n.º 20
0
func main() {
	tb := thunderbird.New()
	ch := &RoomChannel{tb}
	tb.HandleChannel("room", ch)

	router := mux.NewRouter()
	router.HandleFunc("/", serveHome).Methods("GET")
	router.Handle("/ws", tb.HTTPHandler())

	n := negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
		negroni.NewStatic(http.Dir("../client/lib")), // serve thunderbird.js
		negroni.NewStatic(http.Dir("public")),        // serve other assets
	)
	n.UseHandler(router)

	n.Run(":" + os.Getenv("PORT"))
}
Ejemplo n.º 21
0
func main() {
	router := mux.NewRouter()
	router.HandleFunc("/black-and-gray", ShowCars)
	n := negroni.New()
	n.Use(negroni.NewLogger())
	// include the gzip middleware above any other middleware that alters response body
	n.Use(gzip.Gzip(gzip.DefaultCompression))
	n.Use(negroni.NewRecovery())
	n.Use(negroni.NewStatic(http.Dir("public")))
	n.UseHandler(router)
	n.Run(":8888")
}
Ejemplo n.º 22
0
func main() {
	n := negroni.New()
	n.Use(negronilogrus.NewMiddleware())
	n.Use(negroni.NewStatic(http.Dir("public")))
	render := render.New(render.Options{})
	renderer := context.NewRender(render)
	n.Use(renderer)
	n.UseHandler(router.API())

	go handlers.Hub.Run()
	n.Run(":3000")
}
Ejemplo n.º 23
0
func main() {
	ren := render.New(render.Options{
		Layout:        "shared/layout",
		IsDevelopment: true,
	})

	//sessions
	store := cookiestore.New([]byte("secret"))

	//db
	// db, err := sqlx.Connect("postgres", os.Getenv("CONNECTIONSTRING"))
	db, err := sqlx.Connect("postgres", "user=travisjones dbname=cm_app sslmode=disable")
	if err != nil {
		log.Println("Error initializing database...")
		log.Fatalln(err)
	}

	c := ctx{db, ren}

	n := negroni.New()
	nauth := negroni.New()

	//routers
	router := mux.NewRouter()
	authRouter := mux.NewRouter()

	//AUTHORIZED ROUTES
	authRouter.HandleFunc("/", c.Home)
	router.Handle("/", nauth).Methods("GET")

	//OPEN ROUTES
	router.HandleFunc("/account/login", c.Login).Methods("GET")
	router.HandleFunc("/account/login", c.LoginPost).Methods("POST")
	router.HandleFunc("/account/signup", c.Signup).Methods("GET")
	router.HandleFunc("/account/signup", c.SignupPost).Methods("POST")
	router.HandleFunc("/account/logout", c.Logout).Methods("GET")

	//Middleware
	nauth.Use(negroni.HandlerFunc(RequireAuth))
	nauth.UseHandler(authRouter)

	//Sessions
	n.Use(sessions.Sessions("authex", store))

	n.Use(negroni.NewStatic(http.Dir("public")))

	n.UseHandler(router)

	n.Run(
		fmt.Sprint(":", os.Getenv("PORT")),
	)

}
Ejemplo n.º 24
0
// New returns a new Handler instance.
func New(dir string) *Handler {
	if dir == "" {
		dir = DefaultDirectory
	}

	s := negroni.NewStatic(http.Dir(dir))
	s.IndexFile = ""
	return &Handler{
		Dir:    dir,
		Index:  DefaultIndex,
		static: s,
	}
}
Ejemplo n.º 25
0
func main() {

	store := cookiestore.New([]byte("secretkey789"))
	router := LoadRoutes()
	n := negroni.Classic()
	static := negroni.NewStatic(http.Dir("static"))
	static.Prefix = "/static"
	n.Use(static)
	n.Use(negroni.HandlerFunc(MgoMiddleware))
	n.Use(sessions.Sessions("global_session_store", store))
	n.UseHandler(router)
	n.Run(":3000")

}
Ejemplo n.º 26
0
func Start() {
	r := mux.NewRouter().StrictSlash(true)
	r.NotFoundHandler = http.HandlerFunc(errorHandler)

	/*
	 *
	 *  ROUTES
	 */
	r.HandleFunc("/", mainPageHandler)
	r.HandleFunc("/upload", uploadHandler)
	r.HandleFunc("/apps", appsPageHandler)
	r.HandleFunc("/favicon.ico", favIcoHandler)
	r.HandleFunc("/img/{id}", imageHandler)
	r.HandleFunc("/{id}", imagePageHandler)
	r.HandleFunc("/api/upload", apiUploadHandler)
	r.HandleFunc("/error", errorHandler)

	n := negroni.New(
		negroni.NewRecovery(),
		negroni.HandlerFunc(MiddleWare),
		negroni.NewLogger(),
		negroni.NewStatic(http.Dir(os.Getenv("APP_LOCATION"))),
		negroni.NewStatic(http.Dir("public")),
	)
	n.UseHandler(r)

	go func(n http.Handler) {
		cio.PrintMessage(0, "https: Running on port 8001...")
		err := http.ListenAndServeTLS(":8001", "http/ssl/cert.pem", "http/ssl/key.pem", n)
		if err != nil {
			log.Fatal(err)
		}
	}(n)

	cio.PrintMessage(0, "http: Running on port 8000...")
	http.ListenAndServe(":8000", n)
}
Ejemplo n.º 27
0
func main() {

	settings := evergreen.GetSettingsOrExit()
	home := evergreen.FindEvergreenHome()
	uis, err := ui.New(settings, home)
	if err != nil {
		fmt.Println("Failed to create ui server: %v", err)
		os.Exit(1)
	}
	router, err := uis.NewRouter()
	if err != nil {
		fmt.Println("Failed to create router:", err)
		os.Exit(1)
	}

	webHome := filepath.Join(uis.Home, "public")

	functionOptions := ui.FuncOptions{webHome, uis.Settings.Ui.HelpUrl, true, router}

	functions, err := ui.MakeTemplateFuncs(functionOptions, uis.Settings.SuperUsers)
	htmlFunctions := htmlTemplate.FuncMap(functions)
	textFunctions := textTemplate.FuncMap(functions)

	if err != nil {
		fmt.Println("Failed to create template function map:", err)
		os.Exit(1)
	}

	uis.Render = render.New(render.Options{
		Directory:    filepath.Join(uis.Home, ui.WebRootPath, ui.Templates),
		DisableCache: !uis.Settings.Ui.CacheTemplates,
		HtmlFuncs:    htmlFunctions,
		TextFuncs:    textFunctions,
	})
	err = uis.InitPlugins()
	if err != nil {
		fmt.Println("WARNING: Error initializing plugins:", err)
	}

	n := negroni.New()
	n.Use(negroni.NewStatic(http.Dir(webHome)))
	n.Use(ui.NewLogger())
	n.Use(negroni.HandlerFunc(ui.UserMiddleware(uis.UserManager)))
	n.UseHandler(router)
	graceful.Run(uis.Settings.Ui.HttpListenAddr, requestTimeout, n)
	evergreen.Logger.Logf(slogger.INFO, "UI server cleanly terminated")
}
Ejemplo n.º 28
0
func newServerStack(engine *engine.Engine) *negroni.Negroni {
	context := handlers.NewContext(engine)

	router := mux.NewRouter().StrictSlash(true)
	router.HandleFunc("/", context.IndexHandler).Methods("GET")
	router.HandleFunc("/execute", context.ExecuteHandler).Methods("POST")
	router.HandleFunc("/executews", context.ExecuteWSHandler).Methods("GET")
	router.HandleFunc("/info", context.InfoHandler).Methods("GET")

	server := negroni.New(xrequestid.New(16),
		context,
		negronilogrus.NewCustomMiddleware(logrus.InfoLevel, &logrus.JSONFormatter{}, "straitjacket"),
		cors.Default(),
		negroni.NewStatic(http.Dir("public")))
	server.UseHandler(router)
	return server
}
Ejemplo n.º 29
0
func main() {
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	// Middleware stack
	n := negroni.New(
		negroni.NewRecovery(),
		negroni.HandlerFunc(LetMeGoogleThatForYou),
		negroni.HandlerFunc(MyMiddleware),
		negroni.NewLogger(),
		negroni.NewStatic(http.Dir("public")),
	)

	n.Run(":" + port)
}
Ejemplo n.º 30
0
func startServer(context Context) {
	mux := http.NewServeMux()
	mux.HandleFunc("/status", StatusHandler)

	server := negroni.New()
	server.Use(negroni.NewRecovery())
	server.Use(logger.NewMiddlewareLogger(context.lg))

	server.Use(negroni.NewStatic(http.Dir("staging")))

	server.UseHandler(mux)

	p := fmt.Sprintf(":%d", context.port)
	context.lg.Info("starting server at port: %s", p)

	server.Run(p)
}