Example #1
0
func main() {
	var err error
	db, err = sqlx.Connect("postgres", "user=postgres password=postgres dbname=messenger sslmode=disable")
	if err != nil {
		log.Fatalln(err)
	}
	CreateSchema(false)

	r := mux.NewRouter()
	authBase := mux.NewRouter()
	apiBase := mux.NewRouter()
	auth := authBase.PathPrefix("/auth").Subrouter()
	api := apiBase.PathPrefix("/api").Subrouter()

	r.PathPrefix("/auth").Handler(negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
		negroni.Wrap(authBase),
	))

	jwtSecret = "a very secret string"
	// must be authenticated to  use api routes
	jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
		ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
			return []byte(jwtSecret), nil
		},
		SigningMethod: jwt.SigningMethodHS256,
		UserProperty:  "jwt_user",
	})
	r.PathPrefix("/api").Handler(negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
		negroni.HandlerFunc(jwtMiddleware.HandlerWithNext),
		negroni.Wrap(apiBase),
	))

	// used to check if server is live
	auth.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "pong")
	}).Methods("POST")

	auth.Path("/signup").HandlerFunc(Signup).Methods("POST")
	auth.Path("/login").HandlerFunc(Login).Methods("POST")

	api.Path("/messages").HandlerFunc(NewMessage).Methods("POST")
	api.HandleFunc("/{user}/messages", GetUsersMessages).Methods("GET")

	log.Fatal(http.ListenAndServe(":8080", r))

}
Example #2
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
}
Example #3
0
File: app.go Project: 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}
}
Example #4
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)
}
func getNegroniHandlers(ctx *RouterContext.RouterContext, router *mux.Router) []negroni.Handler {
	tmpArray := []negroni.Handler{}

	// fullRecoveryStackMessage := GlobalConfigSettings.Common.DevMode

	routerRecoveryWrapper := &tmpRouterRecoveryWrapper{ctx.Logger}

	// tmpArray = append(tmpArray, gzip.Gzip(gzip.DefaultCompression))
	tmpArray = append(tmpArray, NewRecovery(routerRecoveryWrapper.onRouterRecoveryError)) //recovery.JSONRecovery(fullRecoveryStackMessage))
	tmpArray = append(tmpArray, negroni.NewLogger())

	if ctx.Settings.IsDevMode() {
		middleware := stats.New()
		router.HandleFunc("/stats.json", func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/json")

			stats := middleware.Data()

			b, _ := json.Marshal(stats)

			w.Write(b)
		})
		tmpArray = append(tmpArray, middleware)
	}

	return tmpArray
}
Example #6
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))
}
Example #7
0
func main() {

	//init datasotre
	datastore.Connect(true, false)
	defer datastore.Close()

	//define routes
	m := http.NewServeMux()
	m.Handle("/api/", http.StripPrefix("/api", handlers.HandleAPI()))
	m.Handle("/", handlers.HandleWEB())

	//create negroni middleware
	n := negroni.New()
	n.Use(negroni.NewRecovery())
	n.Use(negroni.NewLogger())

	//add security
	n.Use(negroni.HandlerFunc(secureMiddleware.HandlerFuncWithNext))

	//add static content from public folder, index.html, seo files and favicon
	//n.Use(negroni.NewStatic(http.Dir("public")))

	//add application handlers
	n.UseHandler(m)

	//running the server
	n.Run(":8000")
}
Example #8
0
func main() {

	// Config
	// ----------------------------

	// Set the port.
	port := os.Getenv("PORT")
	if port == "" {
		port = "3000"
	}

	// Object Graph
	// ----------------------------
	app := app.Ioc{}
	app.ConfigService = services.NewConfigService()
	app.DatabaseService = services.NewDatabaseService(&app)
	app.DaysController = controllers.NewDaysController(&app)

	// Router
	// ----------------------------
	router := routes.NewRouter(&app)

	// Do we want to use negroni again? Meh ... what about another way to do recovery
	n := negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
	)
	n.UseHandler(router)

	// Server
	// ----------------------------
	n.Run(":" + port)

}
Example #9
0
func main() {
	fmt.Printf("hyperion-dashboard%s\n", buildVersion)

	httpAddr := flag.String("http-address", "127.0.0.1:12300", "<addr>:<port> to listen on")
	dsn := flag.String("db", "", "Database source name")
	flag.Parse()

	dataSource := *dsn
	if dataSource == "" {
		if os.Getenv("HYPERION_DB") != "" {
			dataSource = os.Getenv("HYPERION_DB")
		}
	}

	if dataSource == "" {
		flag.Usage()
		log.Fatal("--db or HYPERION_DB not found")
	}

	db, err := NewDBConn(dataSource)
	if err != nil {
		log.Fatal(err.Error())
	}

	router := mux.NewRouter()
	router.HandleFunc("/", db.RecordsHandler)

	recovery := negroni.NewRecovery()
	logger := negroni.NewLogger()

	n := negroni.New(recovery, logger)
	n.UseHandler(router)
	n.Run(*httpAddr)
}
Example #10
0
func main() {
	// render
	r := render.New(render.Options{})

	// middleware
	n := negroni.New(
		negroni.NewLogger(),
		negroni.NewRecovery(),
	)

	// database
	sess, err := db.Open(sqlite.Adapter, sqlite.ConnectionURL{
		Database: "test.db",
	})
	if err != nil {
		log.Fatal(err)
	}
	defer sess.Close()

	// router
	router := httprouter.New()

	groupsController := controllers.NewGroupsController(r, sess)
	router.GET("/api/v1/groups.json", groupsController.Index)
	router.POST("/api/v1/groups.json", groupsController.Create)

	n.UseHandler(router)
	n.Run(":" + strconv.Itoa(getPort()))
}
Example #11
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}
}
Example #12
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"))
}
// initialize Negroni (middleware, handler)
func initNegroni(handler http.Handler) *negroni.Negroni {
	n := negroni.New()
	n.Use(negroni.NewRecovery())
	n.Use(negroni.NewLogger())
	n.Use(ContentTypeMiddleware())
	n.UseHandler(handler)
	return n
}
Example #14
0
func main() {
	n := negroni.New(
		negroni.NewRecovery(),
		negroni.HandlerFunc(MyMiddleware),
		negroni.NewLogger(),
		negroni.NewStatic(http.Dir("public")),
	)
	n.Run(":8080")
}
Example #15
0
func main() {
	if *hotReload {
		// set up file watcher
		log.Printf("setting up file watcher for %s\n", *hooksFilePath)

		var err error

		watcher, err = fsnotify.NewWatcher()
		if err != nil {
			log.Fatal("error creating file watcher instance", err)
		}

		defer watcher.Close()

		go watchForFileChange()

		err = watcher.Add(*hooksFilePath)
		if err != nil {
			log.Fatal("error adding hooks file to the watcher", err)
		}
	}

	l := negroni.NewLogger()
	l.Logger = log.New(os.Stdout, "[webhook] ", log.Ldate|log.Ltime)

	negroniRecovery := &negroni.Recovery{
		Logger:     l.Logger,
		PrintStack: true,
		StackAll:   false,
		StackSize:  1024 * 8,
	}

	n := negroni.New(negroniRecovery, l)

	router := mux.NewRouter()

	var hooksURL string

	if *hooksURLPrefix == "" {
		hooksURL = "/{id}"
	} else {
		hooksURL = "/" + *hooksURLPrefix + "/{id}"
	}

	router.HandleFunc(hooksURL, hookHandler)

	n.UseHandler(router)

	if *secure {
		log.Printf("starting secure (https) webhook on %s:%d", *ip, *port)
		log.Fatal(http.ListenAndServeTLS(fmt.Sprintf("%s:%d", *ip, *port), *cert, *key, n))
	} else {
		log.Printf("starting insecure (http) webhook on %s:%d", *ip, *port)
		log.Fatal(http.ListenAndServe(fmt.Sprintf("%s:%d", *ip, *port), n))
	}

}
Example #16
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))
}
Example #17
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)
}
Example #18
0
File: main.go Project: Aetema/oj
func main() {
	mux := Routes()
	n := negroni.New(
		negroni.NewRecovery(),
		negroni.HandlerFunc(middleware.Permission),
		negroni.NewLogger(),
	)
	n.UseHandler(mux)
	n.Run(":8080")
}
Example #19
0
func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", VoteHandler)

	n := negroni.New(
		negroni.NewLogger(),
		negroni.Wrap(mux),
	)
	n.Run(":" + os.Getenv("PORT"))
}
Example #20
0
func init() {
	mux := http.NewServeMux()
	mux.HandleFunc("/serve", serveHandler)
	mux.HandleFunc("/", indexHandler)

	n := negroni.New()
	n.Use(negroni.NewRecovery())
	n.Use(negroni.NewLogger())
	n.UseHandler(mux)
	http.Handle("/", n)
}
Example #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")
}
Example #22
0
/**
 * Constructs a new server object.
 */
func NewCoreServer() CoreServer {
	server := CoreServer{
		Router:     mux.NewRouter(),
		Middleware: negroni.New(),
	}

	/**
	 * Add some Negroni middleware.
	 */
	server.Middleware.Use(negroni.NewLogger())
	// TODO: Need to change key.
	storage := cookiestore.New([]byte("temporary"))
	server.Middleware.Use(sessions.Sessions("userprofile", storage))
	config := (oauth2.Config)(GetClientConfig())
	server.Middleware.Use(oauth2.Google(&config))

	/**
	 * Mux describing routes that require the user to be logged in via
	 * oauth first.
	 */
	secureMux := http.NewServeMux()
	// Core app handlers; these require the user to be logged in.
	secureMux.HandleFunc("/app/fetch", fetch)
	secureMux.HandleFunc("/app", app_handler)

	secure := negroni.New()
	secure.Use(oauth2.LoginRequired())
	secure.UseHandler(secureMux)

	/**
	 * Handlers that don't require authentication.
	 */
	server.Router.HandleFunc("/auth", auth_handler)
	// Static content handler
	server.Router.PathPrefix("/static").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("web/"))))
	// Simple redirect handler
	server.Router.HandleFunc("/", main_handler)

	/**
	 * And now connect everything together and call it a day.
	 */
	// Make sure the core router knows to let the secure router handle these routes.
	server.Router.Handle("/app/fetch", secure)
	server.Router.Handle("/app", secure)
	// Set negroni handler
	server.Middleware.UseHandler(server.Router)

	return server
}
Example #23
0
File: main.go Project: kshlm/heketi
func main() {

	// Get a mock node server
	plugin := plugins.NewPlugin("glusterfs")

	//
	nodeserver := handlers.NewNodeServer(plugin)
	volumeserver := handlers.NewVolumeServer(plugin)

	r := volumeserver.VolumeRoutes()
	r = append(r, nodeserver.NodeRoutes()...)

	// Create a router and do not allow any routes
	// unless defined.
	router := mux.NewRouter().StrictSlash(true)
	for _, route := range r {

		// Add routes from the table
		router.
			Methods(route.Method).
			Path(route.Pattern).
			Name(route.Name).
			Handler(route.HandlerFunc)

	}

	// Use negroni to add middleware.  Here we add two
	// middlewares: Recovery and Logger, which come with
	// Negroni
	n := negroni.New(negroni.NewRecovery(), negroni.NewLogger())
	n.UseHandler(router)

	// Shutdown on CTRL-C signal
	// For a better cleanup, we should shutdown the server and
	signalch := make(chan os.Signal, 1)
	signal.Notify(signalch, os.Interrupt)
	go func() {
		select {
		case <-signalch:
			fmt.Printf("Shutting down...")
			plugin.Close()
			os.Exit(0)
		}
	}()

	// Start the server.
	log.Fatal(http.ListenAndServe(":8080", n))

}
Example #24
0
// NewServer - init http server
func NewServer() *http.Server {
	n := negroni.New()
	n.Use(negroni.NewLogger())
	// Setup routes
	router := pat.New()
	router.Get("/api/predict/:id", http.HandlerFunc(predict))
	// Add the router action
	n.UseHandler(router)
	Server := &http.Server{
		Addr:           ":8080",
		Handler:        n,
		MaxHeaderBytes: 1 << 20,
	}
	return Server
}
Example #25
0
//InitWebServer ... Initialize a web server based on the configuration
func (base *BaseRouter) InitWebServer(port int, router interface{}) error {
	var err error
	if base.WebServer == "negroni" {
		base.MuxRouter = mux.NewRouter()
		base.NegroniServer = negroni.New(negroni.NewLogger())
		base.NegroniServer.Use(recovery.JSONRecovery(true))
		base.NegroniServer.UseHandler(base.MuxRouter)
		base.NegroniServer.Run(fmt.Sprintf(":%d", port))
	}
	if base.WebServer == "ant0ine" {
		base.APIServer = rest.NewApi()
		base.APIServer.Use(rest.DefaultDevStack...)
	}
	return err
}
Example #26
0
func main() {

	var app rest.Application

	// Setup a new GlusterFS application
	app = glusterfs.NewApp()
	if app == nil {
		fmt.Println("Unable to start application")
		os.Exit(1)
	}

	// Create a router and do not allow any routes
	// unless defined.
	router := mux.NewRouter().StrictSlash(true)
	err := app.SetRoutes(router)
	if err != nil {
		fmt.Println("Unable to create http server endpoints")
		os.Exit(1)
	}

	// Use negroni to add middleware.  Here we add two
	// middlewares: Recovery and Logger, which come with
	// Negroni
	n := negroni.New(negroni.NewRecovery(), negroni.NewLogger())
	n.UseHandler(router)

	// Shutdown on CTRL-C signal
	// For a better cleanup, we should shutdown the server and
	signalch := make(chan os.Signal, 1)
	signal.Notify(signalch, os.Interrupt)
	go func() {
		select {
		case <-signalch:
			fmt.Printf("Shutting down...\n")
			// :TODO: Need to stop the server before closing the app

			// Close the application
			app.Close()

			// Quit
			os.Exit(0)
		}
	}()

	// Start the server.
	log.Fatal(http.ListenAndServe(":8080", n))

}
Example #27
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)
}
Example #28
0
func New() http.Handler {
	// set up handlers
	http.HandleFunc("/1/setpoint.json", makeHandler(setpointHandler))
	http.HandleFunc("/1/sleep.json", makeHandler(sleepHandler))
	http.HandleFunc("/1/smooth.json", makeHandler(smoothHandler))
	http.HandleFunc("/1/setpid.json", makeHandler(setpidHandler))
	http.Handle("/1/data.json", negroni.New(
		gzip.Gzip(gzip.DefaultCompression),
		negroni.Wrap(makeHandler(dataHandler)),
	))

	// use negroni
	n := negroni.New(negroni.NewRecovery(), negroni.NewLogger())
	n.UseHandler(http.DefaultServeMux)

	return http.Handler(n)
}
Example #29
0
func main() {
	controller.Init()
	mux := http.NewServeMux()
	mux.HandleFunc("/", controller.HandlHome)
	mux.HandleFunc("/login", controller.HandlLogin)
	mux.HandleFunc("/signUp", controller.HandlSignUp)

	//add static file server for include static files
	mux.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
	n := negroni.New(
		negroni.NewRecovery(),
		negroni.HandlerFunc(middleware.Permission),
		negroni.NewLogger(),
	)
	n.UseHandler(mux)
	n.Run(":8080")
}
Example #30
0
func main() {
	env = os.Getenv("XTREMEPAY_SERVICE")
	router := mux.NewRouter()
	n := negroni.New(negroni.NewLogger())
	viperConfig := viper.New()

	store := cookiestore.New([]byte("secret123"))
	n.Use(sessions.Sessions("my_session", store))

	c := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
	})

	serviceManager := ServiceManager{router, n, viperConfig, c}
	serviceManager.LoadConfig(env)
	serviceManager.LoadService()

}