// 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{ IndentJSON: true, StreamingJSON: true, }) // Establish connection to DB as specified in database.go db := NewDB() models.New(db) // Add middleware to the stack ne.Use(negroni.NewRecovery()) ne.Use(negroni.NewLogger()) ne.UseHandler(ro) // Return a new App struct with all these things. return &App{ne, ro, re} }
// RunServer runs the app func RunServer() error { cnf, db, err := initConfigDB(true, true) if err != nil { return err } defer db.Close() if err := initServices(cnf, db); err != nil { return err } // Start a classic negroni app app := negroni.New() app.Use(negroni.NewRecovery()) app.Use(negroni.NewLogger()) app.Use(gzip.Gzip(gzip.DefaultCompression)) app.Use(negroni.NewStatic(http.Dir("public"))) // Create a router instance router := mux.NewRouter() // Add routes healthService.RegisterRoutes(router, "/v1") oauthService.RegisterRoutes(router, "/v1/oauth") webService.RegisterRoutes(router, "/web") // Set the router app.UseHandler(router) // Run the server on port 8080, gracefully stop on SIGTERM signal graceful.Run(":8080", 5*time.Second, app) return nil }
// RunServer runs the app func RunServer() error { cnf, db, err := initConfigDB(true, true) if err != nil { return err } defer db.Close() // Initialise the health service healthService := health.NewService(db) // Initialise the oauth service oauthService := oauth.NewService(cnf, db) // Initialise the email service emailService := email.NewService(cnf) // Initialise the accounts service accountsService := accounts.NewService( cnf, db, oauthService, emailService, nil, // accounts.EmailFactory ) // Initialise the facebook service facebookService := facebook.NewService( cnf, db, accountsService, nil, // facebook.Adapter ) // Start a negroni app app := negroni.New() app.Use(negroni.NewRecovery()) app.Use(negroni.NewLogger()) app.Use(gzip.Gzip(gzip.DefaultCompression)) // Create a router instance router := mux.NewRouter() // Register routes healthService.RegisterRoutes(router, "/v1") oauthService.RegisterRoutes(router, "/v1/oauth") accountsService.RegisterRoutes(router, "/v1") facebookService.RegisterRoutes(router, "/v1/facebook") // Set the router app.UseHandler(router) // Run the server on port 8080, gracefully stop on SIGTERM signal graceful.Run(":8080", 5*time.Second, app) return nil }
// NewApp returns a pointer to an application instance. These // instances have reasonable defaults and include middleware to: // recover from panics in handlers, log information about the request, // and gzip compress all data. Users must specify a default version // for new methods. func NewApp() *APIApp { a := &APIApp{ StrictSlash: true, defaultVersion: -1, // this is the same as having no version prepended to the path. port: 3000, } a.AddMiddleware(negroni.NewRecovery()) a.AddMiddleware(NewAppLogger()) a.AddMiddleware(gzip.Gzip(gzip.DefaultCompression)) return a }
func (c *ServerCommand) buildMiddleware() error { logger, err := c.getLogrusMiddleware() if err != nil { return err } n := negroni.New() n.Use(negroni.NewRecovery()) n.Use(logger) n.UseHandler(c.s.Handler) c.s.Handler = n return nil }
// RunServer runs the app func RunServer() error { cnf, db, err := initConfigDB(true, true) if err != nil { return err } defer db.Close() // Initialise the health service healthService := health.NewService(db) // Initialise the oauth service oauthService := oauth.NewService(cnf, db) // Initialise the web service webService := web.NewService(cnf, oauthService) // Start a classic negroni app app := negroni.New() app.Use(negroni.NewRecovery()) app.Use(negroni.NewLogger()) app.Use(gzip.Gzip(gzip.DefaultCompression)) app.Use(negroni.NewStatic(http.Dir("public"))) // Create a router instance router := mux.NewRouter() // Add routes for the health service (healthcheck endpoint) health.RegisterRoutes(router, healthService) // Add routes for the oauth service (REST tokens endpoint) oauth.RegisterRoutes(router, oauthService) // Add routes for the web package (register, login authorize web pages) web.RegisterRoutes(router, webService) // Set the router app.UseHandler(router) // Run the server on port 8080 app.Run(":8080") return nil }
// BuildWebServer constructs a new web server with the right DAO and spirits handler func BuildWebServer(db string, daoType int, statisticsDuration time.Duration) (*negroni.Negroni, error) { // spirit dao dao, err := dao.GetSpiritDAO(db, daoType) if err != nil { logger.WithField("error", err).WithField("connection string", db).Fatal("unable to connect to mongo db") return nil, err } // web server n := negroni.New() // new handler handler := NewSpiritHandler(dao) // new router router := NewRouter(handler) // add middleware for logging n.Use(negronilogrus.NewMiddlewareFromLogger(logger.StandardLogger(), "spirit")) // add recovery middleware in case of panic in handler func recovery := negroni.NewRecovery() recovery.PrintStack = false n.Use(recovery) // add statistics middleware n.Use(NewStatisticsMiddleware(statisticsDuration)) // add as many middleware as you like // handler goes last n.UseHandler(router) return n, nil }
// httpServer returns an http server func (s *Server) httpServer(log *logrus.Entry) *http.Server { addr := fmt.Sprintf("%s:%d", s.config.HTTPServer.Host, s.config.HTTPServer.Port) log.Debugf("http server will listen on: %s", addr) mux := mux.NewRouter() for _, route := range []struct { // name of the route name string // path of the route path string // allowed methods for this route methods string // handler is the http handler to run if the route matches handler func(http.ResponseWriter, *http.Request) // excluded tells if the route should be added to the router, // it's in the negative form so that the default behaviour is to add // the route to the router excluded bool }{ { name: "GetMovies", path: "/movies", methods: "GET", handler: s.movieIds, }, { name: "GetMovie", path: "/movies/{id}", methods: "GET", handler: s.getMovieDetails, }, { name: "DeleteMovie", path: "/movies/{id}", methods: "DELETE", handler: s.deleteMovie, }, { name: "DownloadMovie", path: "/movies/{id}/download", methods: "GET", handler: s.serveMovie, excluded: !s.config.HTTPServer.ServeFiles, }, { name: "GetShows", path: "/shows", methods: "GET", handler: s.showIds, }, { name: "GetShow", path: "/shows/{id}", methods: "GET", handler: s.getShowDetails, }, { name: "GetSeason", path: "/shows/{id}/seasons/{season:[0-9]+}", methods: "GET", handler: s.getSeasonDetails, }, { name: "GetEpisode", path: "/shows/{id}/seasons/{season:[0-9]+}/episodes/{episode:[0-9]+}", methods: "GET", handler: s.getShowEpisodeIDDetails, }, { name: "DeleteEpisode", path: "/shows/{id}/seasons/{season:[0-9]+}/episodes/{episode:[0-9]+}", methods: "DELETE", handler: s.deleteEpisode, }, { name: "DownloadEpisode", path: "/shows/{id}/seasons/{season:[0-9]+}/episodes/{episode:[0-9]+}/download", methods: "GET", handler: s.serveShow, excluded: !s.config.HTTPServer.ServeFiles, }, { name: "Wishlist", path: "/wishlist", methods: "GET", handler: s.wishlist, }, { name: "AddTorrent", path: "/torrents", methods: "POST", handler: s.addTorrent, }, } { if route.excluded { continue } // Register the route mux.HandleFunc(route.path, route.handler).Name(route.name).Methods(route.methods) } n := negroni.New() // Panic recovery n.Use(negroni.NewRecovery()) // Use logrus as logger n.Use(negronilogrus.NewMiddlewareFromLogger(s.log.Logger, "httpServer")) // gzip compression n.Use(gzip.Gzip(gzip.DefaultCompression)) // Add basic auth if configured if s.config.HTTPServer.BasicAuth { log.Info("server will require basic authentication") n.Use(NewBasicAuthMiddleware(s.config.HTTPServer.BasicAuthUser, s.config.HTTPServer.BasicAuthPassword)) } // Add token auth middleware if token configuration file specified if s.tokenManager != nil { n.Use(token.NewMiddleware(s.tokenManager, mux)) mux.HandleFunc("/tokens/allowed", s.tokenGetAllowed).Name("TokenGetAllowed") } // Wrap the router n.UseHandler(mux) return &http.Server{Addr: addr, Handler: n} }