// BuildRoutes returns the routes for the application. func BuildRoutes() http.Handler { router := mux.NewRouter() router.HandleFunc("/", HomeHandler) router.HandleFunc("/login-success", LoginSuccessHandler) router.HandleFunc("/verify", VerifyHandler) router.HandleFunc("/logout", LogoutHandler) router.HandleFunc("/game", GameHandler) // profile routes with LoginRequiredMiddleware profileRouter := mux.NewRouter() profileRouter.HandleFunc("/profile", ProfileHandler) router.PathPrefix("/profile").Handler(negroni.New( negroni.HandlerFunc(LoginRequiredMiddleware), negroni.Wrap(profileRouter), )) // apply the base middleware to the main router n := negroni.New( negroni.HandlerFunc(CsrfMiddleware), negroni.HandlerFunc(UserMiddleware), ) n.UseHandler(router) return n }
//InitRoutes sets up our routes, whether anonymous or authenticated. //Utilizing Negroni so we can have multiple handlers, each one with the ability to call the next. func InitRoutes() *mux.Router { router := mux.NewRouter().StrictSlash(true) //anonymous routes //Get Environment router.Handle("/", negroni.New( negroni.HandlerFunc(controllers.GetRoute), )).Methods("GET") //Get Milestones By DealID router.Handle("/milestones/complete/{dealGUID}", negroni.New( negroni.HandlerFunc(controllers.GetDealCompletedMilestonesByDealGUID), )).Methods("GET") //Get Milestones with complete status By DealID router.Handle("/milestones/{dealGUID}", negroni.New( negroni.HandlerFunc(controllers.GetMilestonesByDealGUID), )).Methods("GET") //Post events for a deal router.Handle("/event/{dealGUID}/{eventName}", negroni.New( negroni.HandlerFunc(controllers.DealEventHandler), )).Methods("GET") //authenticated routes //... return router }
func InitPost(r *mux.Router) { l4g.Debug("Initializing post api routes") r.Handle("/posts/{post_id}", negroni.New( negroni.HandlerFunc(RequireAuth), negroni.HandlerFunc(getPost), )).Methods("GET") sr := r.PathPrefix("/channels/{id}").Subrouter() sr.Handle("/create", negroni.New( negroni.HandlerFunc(RequireAuth), negroni.HandlerFunc(createPost), )).Methods("POST") sr.Handle("/update", negroni.New( negroni.HandlerFunc(RequireAuth), negroni.HandlerFunc(updatePost), )).Methods("POST") // {offset:[0-9]+}/{limit:[0-9]+} sr.Handle("/posts/", negroni.New( negroni.HandlerFunc(RequireAuth), negroni.HandlerFunc(getPosts), )).Methods("GET") }
func (a *Api) Run() error { globalMux := http.NewServeMux() router := mux.NewRouter() router.HandleFunc("/", a.index).Methods("GET") router.HandleFunc("/create", a.create).Methods("POST") router.HandleFunc("/ip", a.getIP).Methods("GET") router.HandleFunc("/state", a.getState).Methods("GET") router.HandleFunc("/start", a.start).Methods("GET") router.HandleFunc("/kill", a.kill).Methods("GET") router.HandleFunc("/remove", a.remove).Methods("GET") router.HandleFunc("/restart", a.restart).Methods("GET") router.HandleFunc("/stop", a.stop).Methods("GET") // enable auth if token is present if a.config.AuthToken != "" { am := auth.NewAuthMiddleware(a.config.AuthToken) globalMux.Handle("/", negroni.New( negroni.HandlerFunc(am.Handler), negroni.Wrap(http.Handler(router)), )) } else { globalMux.Handle("/", router) } log.Infof("rivet version %s", version.FULL_VERSION) log.Infof("listening: addr=%s", a.config.ListenAddr) n := negroni.New() n.UseHandler(globalMux) return http.ListenAndServe(a.config.ListenAddr, n) }
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)) }
func SetAuthenticationRoutes(router *mux.Router) *mux.Router { tokenRouter := mux.NewRouter() tokenRouter.Handle("/api/auth/token/new", negroni.New( negroni.HandlerFunc(controllers.Login), )).Methods("POST") tokenRouter.Handle("/api/auth/logout", negroni.New( negroni.HandlerFunc(auth.RequireTokenAuthentication), negroni.HandlerFunc(controllers.Logout), )) tokenRouter.Handle("/api/auth/token/refresh", negroni.New( negroni.HandlerFunc(auth.RequireTokenAuthentication), negroni.HandlerFunc(controllers.RefreshToken), )).Methods("GET") tokenRouter.Handle("/api/auth/token/validate", negroni.New( negroni.HandlerFunc(auth.RequireTokenAuthentication), negroni.HandlerFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { w.WriteHeader(http.StatusOK) }), )) router.PathPrefix("/api/auth").Handler(negroni.New( negroni.Wrap(tokenRouter), )) return router }
// Routing ... list of routing services func (c AccountRouter) Routing(router *mux.Router, apiprefix string) { baseModel := base.BaseModel{Status: "ACTIVE", CreatedAt: time.Now()} httpUtilFunc := utilFunc.HTTPUtilityFunctions{} account := controllers.AccountController{c.DataStore, baseModel, httpUtilFunc} router.Handle(apiprefix+"/accounts", negroni.New( negroni.HandlerFunc(authentication.RequireTokenAuthentication), negroni.HandlerFunc(account.CreateAccount), )).Methods("POST") router.Handle(apiprefix+"/account/categories", negroni.New( negroni.HandlerFunc(authentication.RequireTokenAuthentication), negroni.HandlerFunc(account.CreateAccount), )).Methods("POST") router.Handle(apiprefix+"/account/fundsource", negroni.New( negroni.HandlerFunc(authentication.RequireTokenAuthentication), negroni.HandlerFunc(account.CreateAccountCategory), )).Methods("POST") router.Handle(apiprefix+"/account/limit", negroni.New( negroni.HandlerFunc(authentication.RequireTokenAuthentication), negroni.HandlerFunc(account.CreateAccountLimit), )).Methods("POST") router.Handle(apiprefix+"/account/funding", negroni.New( negroni.HandlerFunc(authentication.RequireTokenAuthentication), negroni.HandlerFunc(account.CreateAccountFundMapping), )).Methods("POST") }
func main() { var wg sync.WaitGroup wg.Add(3) go func() { n := negroni.New() fmt.Println("Launching server on :3000") graceful.Run(":3000", 0, n) fmt.Println("Terminated server on :3000") wg.Done() }() go func() { n := negroni.New() fmt.Println("Launching server on :3001") graceful.Run(":3001", 0, n) fmt.Println("Terminated server on :3001") wg.Done() }() go func() { n := negroni.New() fmt.Println("Launching server on :3002") graceful.Run(":3002", 0, n) fmt.Println("Terminated server on :3002") wg.Done() }() fmt.Println("Press ctrl+c. All servers should terminate.") wg.Wait() }
func main() { configuration := readConfiguration() dbSession := DBConnect(configuration.MongodbUrl) DBEnsureIndicesAndDefaults(dbSession, configuration.MongodbDatabaseName) // handle all requests by serving a file of the same name fs := http.Dir(configuration.Webapp) fileHandler := http.FileServer(fs) // setup routes router := mux.NewRouter() router.Handle("/", http.RedirectHandler("/webapp/index.html", 302)) router.PathPrefix("/webapp").Handler(http.StripPrefix("/webapp", fileHandler)) authRouterBase := mux.NewRouter() router.PathPrefix("/auth").Handler(negroni.New(DBMiddleware(dbSession, configuration.MongodbDatabaseName), negroni.Wrap(authRouterBase))) authRouter := authRouterBase.PathPrefix("/auth").Subrouter() authRouter.HandleFunc("/login", Login).Methods("POST") apiRouterBase := mux.NewRouter() router.PathPrefix("/api").Handler(negroni.New(DBMiddleware(dbSession, configuration.MongodbDatabaseName), JWTMiddleware(), negroni.Wrap(apiRouterBase))) apiRouter := apiRouterBase.PathPrefix("/api").Subrouter() apiRouter.HandleFunc("/me", Me).Methods("GET") http.ListenAndServe(fmt.Sprintf(":%v", configuration.Port), router) }
// Routing ... list of routing services func (c UserRouter) Routing(router *mux.Router, apiprefix string) { baseModel := base.BaseModel{Status: "ACTIVE", CreatedAt: time.Now()} httpUtilFunc := utilFunc.HTTPUtilityFunctions{} userController := controllers.UserController{baseModel, httpUtilFunc, c.DataStore, c.Logger.Logger} securityController := controllers.SecurityController{baseModel, c.DataStore, httpUtilFunc} // User url mappings router.HandleFunc(apiprefix+"/user", userController.CreateUser).Methods("POST") router.HandleFunc(apiprefix+"/user/activate", userController.ActivateUser).Methods("PATCH") router.Handle(apiprefix+"/user/changepassword", negroni.New( negroni.HandlerFunc(authentication.RequireTokenAuthentication), negroni.HandlerFunc(userController.ChangePassword), )).Methods("PATCH") router.HandleFunc(apiprefix+"/token-auth", securityController.Login).Methods("POST") router.Handle(apiprefix+"/refresh-token-auth", negroni.New( negroni.HandlerFunc(authentication.RequireTokenAuthentication), negroni.HandlerFunc(controllers.RefreshToken), )).Methods("GET") router.Handle(apiprefix+"/logout", negroni.New( negroni.HandlerFunc(authentication.RequireTokenAuthentication), negroni.HandlerFunc(controllers.Logout), )).Methods("GET") }
func Init(apps map[string]interface{}, router *mux.Router) { Applications = apps // /echo/* Endpoints echoRouter := mux.NewRouter() // /* Endpoints pageRouter := mux.NewRouter() for uri, meta := range Applications { switch app := meta.(type) { case EchoApplication: handlerFunc := func(w http.ResponseWriter, r *http.Request) { echoReq := r.Context().Value("echoRequest").(*EchoRequest) echoResp := NewEchoResponse() if echoReq.GetRequestType() == "LaunchRequest" { if app.OnLaunch != nil { app.OnLaunch(echoReq, echoResp) } } else if echoReq.GetRequestType() == "IntentRequest" { if app.OnIntent != nil { app.OnIntent(echoReq, echoResp) } } else if echoReq.GetRequestType() == "SessionEndedRequest" { if app.OnSessionEnded != nil { app.OnSessionEnded(echoReq, echoResp) } } else { http.Error(w, "Invalid request.", http.StatusBadRequest) } json, _ := echoResp.String() w.Header().Set("Content-Type", "application/json;charset=UTF-8") w.Write(json) } if app.Handler != nil { handlerFunc = app.Handler } echoRouter.HandleFunc(uri, handlerFunc).Methods("POST") case StdApplication: pageRouter.HandleFunc(uri, app.Handler).Methods(app.Methods) } } router.PathPrefix("/echo/").Handler(negroni.New( negroni.HandlerFunc(validateRequest), negroni.HandlerFunc(verifyJSON), negroni.Wrap(echoRouter), )) router.PathPrefix("/").Handler(negroni.New( negroni.Wrap(pageRouter), )) }
func (this *StateHandler) RegisterRoutes(mux *bone.Mux, am *handlers.AuthHandler) { mux.Get("/api/state", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(this.Get), )) mux.Post("/api/state", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(this.Post), )) }
func (this *HoverflyModeHandler) RegisterRoutes(mux *bone.Mux, am *handlers.AuthHandler) { mux.Get("/api/v2/hoverfly/mode", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(this.Get), )) mux.Put("/api/v2/hoverfly/mode", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(this.Put), )) }
func main() { //Loads environment variables from a .env file godotenv.Load("environment") var ( clientID = getEnv("OAUTH2_CLIENT_ID", "client_id") clientSecret = getEnv("OAUTH2_CLIENT_SECRET", "client_secret") redirectURL = getEnv("OAUTH2_REDIRECT_URL", "redirect_url") ) secureMux := http.NewServeMux() // Routes that require a logged in user // can be protected by using a separate route handler // If the user is not authenticated, they will be // redirected to the login path. secureMux.HandleFunc("/restrict", func(w http.ResponseWriter, req *http.Request) { token := oauth2.GetToken(req) fmt.Fprintf(w, "OK: %s", token.Access()) }) secure := negroni.New() secure.Use(oauth2.LoginRequired()) secure.UseHandler(secureMux) n := negroni.New() n.Use(sessions.Sessions("my_session", cookiestore.New([]byte("secret123")))) n.Use(oauth2.Google(&oauth2.Config{ ClientID: clientID, ClientSecret: clientSecret, RedirectURL: redirectURL, Scopes: []string{"https://www.googleapis.com/auth/drive"}, })) router := http.NewServeMux() //routes added to mux do not require authentication router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { token := oauth2.GetToken(req) if token == nil || !token.Valid() { fmt.Fprintf(w, "not logged in, or the access token is expired") return } fmt.Fprintf(w, "logged in") return }) //There is probably a nicer way to handle this than repeat the restricted routes again //of course, you could use something like gorilla/mux and define prefix / regex etc. router.Handle("/restrict", secure) n.UseHandler(router) n.Run(":3000") }
func (this *MiddlewareHandler) RegisterRoutes(mux *bone.Mux, am *handlers.AuthHandler) { mux.Get("/api/middleware", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(this.Redirect), )) mux.Post("/api/middleware", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(this.Redirect), )) }
func TestWorkWithNegroni(t *testing.T) { m1 := func(ctx context.Context, w http.ResponseWriter, r *http.Request, next negroni.ContextHandlerFunc) { fmt.Fprint(w, "+middleware1") next(ctx, w, r) } m2 := func(ctx context.Context, w http.ResponseWriter, r *http.Request, next negroni.ContextHandlerFunc) { fmt.Fprint(w, "+middleware2") ctx = context.WithValue(ctx, "m2", "Hahaha") next(ctx, w, r) } m3 := func(ctx context.Context, w http.ResponseWriter, r *http.Request, next negroni.ContextHandlerFunc) { fmt.Fprint(w, "+middleware3") next(ctx, w, r) } h1 := func(ctx context.Context, w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "+handler1:m2=%s", ctx.Value("m2").(string)) } h2 := func(ctx context.Context, w http.ResponseWriter, r *http.Request, ps Params) { fmt.Fprintf(w, "+handler2:ps=%s, m2=%s", ps.ByName("name"), ctx.Value("m2").(string)) } endrouter := New() endrouter.GET("/admin/handler2/:name", h2) endrouter.ContextHandlerFunc("GET", "/admin/handler1", h1) m12 := negroni.New(negroni.HandlerFunc(m1), negroni.HandlerFunc(m2), negroni.WrapCH(negroni.ContextHandlerFunc(h1))) m32 := negroni.New(negroni.HandlerFunc(m3), negroni.HandlerFunc(m2), negroni.WrapCH(endrouter)) root := New() root.ContextHandler("GET", "/", m12) root.ContextHandler("GET", "/admin/*fp", m32) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/", nil) root.ServeHTTP(w, req) if w.Code != http.StatusOK || w.Body.String() != "+middleware1+middleware2+handler1:m2=Hahaha" { t.Errorf("GET / failed: %v", w) } w = httptest.NewRecorder() req, _ = http.NewRequest("GET", "/admin/handler2/lumieru", nil) root.ServeHTTP(w, req) if w.Code != http.StatusOK || w.Body.String() != "+middleware3+middleware2+handler2:ps=lumieru, m2=Hahaha" { t.Errorf("GET /admin/handler2/lumieru failed: %v", w) } w = httptest.NewRecorder() req, _ = http.NewRequest("GET", "/admin/handler1", nil) root.ServeHTTP(w, req) if w.Code != http.StatusOK || w.Body.String() != "+middleware3+middleware2+handler1:m2=Hahaha" { t.Errorf("GET /admin/handler1 failed: %v", w) } }
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")), ) }
func main() { flag.Parse() store.Init() p := func(name string, handler http.HandlerFunc) http.Handler { return prometheus.InstrumentHandler(name, handler) } router := mux.NewRouter() router.Handle("/metrics", prometheus.Handler()) router.Handle("/", p("/", home)) router.Handle("/login", p("/login", login)) router.Handle("/verify", p("/verify", verify)) apiRouter := mux.NewRouter() apiRouter.Handle("/api/logout", p("/logout", logout)) apiRouter.Handle("/api/user", p("/user", user)) apiRouter.Handle("/api/user/project", p("/user/project", userProject)) apiRouter.Handle("/api/project", p("/project", project)) apiRouter.Handle("/api/project/member", p("/task/member", member)) apiRouter.Handle("/api/task", p("/task", task)) apiRouter.Handle("/api/task/worker", p("/task/worker", worker)) apiRouter.Handle("/api/milestone", p("/milestone", milestone)) apiRouter.Handle("/api/friend", p("/friend", friend)) apiRouter.Handle("/api/chat", p("/chat", chat)) apiRouter.HandleFunc("/api/ws", ws) router.PathPrefix("/api").Handler(negroni.New( negroni.HandlerFunc(apiMiddleware), negroni.Wrap(apiRouter), )) adminRouter := mux.NewRouter() adminRouter.Handle("/api/admin/user", p("/admin/user", adminUser)) adminRouter.Handle("/api/admin/project", p("/admin/project", adminProject)) router.PathPrefix("/api/admin").Handler(negroni.New( negroni.HandlerFunc(adminMiddleware), negroni.Wrap(adminRouter), )) go h.run() n := negroni.Classic() n.UseHandler(router) port := os.Getenv("PORT") if port == "" { port = "8080" } n.Run(":" + port) }
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)) }
func SetAuthenticationRoutes(router *mux.Router) *mux.Router { router.HandleFunc("/token-auth", controllers.Login).Methods("POST") router.Handle("/refresh-token-auth", negroni.New( negroni.HandlerFunc(authentication.RequireTokenAuthentication), negroni.HandlerFunc(controllers.RefreshToken), )).Methods("GET") router.Handle("/logout", negroni.New( negroni.HandlerFunc(authentication.RequireTokenAuthentication), negroni.HandlerFunc(controllers.Logout), )).Methods("GET") return router }
func SetRequestRoutes(router *mux.Router) *mux.Router { router.Handle("/request", negroni.New( negroni.HandlerFunc(authentication.RequireTokenAuthentication), negroni.HandlerFunc(controllers.RequestListController), )).Methods("GET") router.Handle("/request", negroni.New( negroni.HandlerFunc(authentication.RequireTokenAuthentication), negroni.HandlerFunc(controllers.RequestShowController), )).Methods("POST") return router }
/** * 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 }
//InitRoutes sets up our routes, whether anonymous or authenticated. //Utilizing Negroni so we can have multiple handlers, each one with the ability to call the next. func InitRoutes() *mux.Router { router := mux.NewRouter().StrictSlash(true) router.Handle("/", negroni.New( negroni.HandlerFunc(controllers.GetRoute), )).Methods("GET") router.Handle("/deal/{dealGuid}", negroni.New( negroni.HandlerFunc(controllers.GetDealByGuid), )).Methods("GET") return router }
func (this *TemplatesHandler) RegisterRoutes(mux *bone.Mux, am *handlers.AuthHandler) { mux.Get("/api/templates", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(this.Get), )) mux.Delete("/api/templates", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(this.Delete), )) mux.Post("/api/templates", negroni.New( negroni.HandlerFunc(am.RequireTokenAuthentication), negroni.HandlerFunc(this.Post), )) }
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) }
func MakeTestServer(dispatcher queueDispatcher) *negroni.Negroni { server := negroni.New() // don't need all the middleware here or logging. mx := mux.NewRouter() initRoutes(mx, formatter, dispatcher, dispatcher, dispatcher) server.UseHandler(mx) return server }
// New creates a REST API server with a given config func New(cfg *Config) (*Server, error) { // pull a few parameters from the configuration passed in by snapd https := cfg.HTTPS cpath := cfg.RestCertificate kpath := cfg.RestKey s := &Server{ err: make(chan error), killChan: make(chan struct{}), addrString: cfg.Address, } if https { var err error s.snapTLS, err = newtls(cpath, kpath) if err != nil { return nil, err } protocolPrefix = "https" } restLogger.Info(fmt.Sprintf("Configuring REST API with HTTPS set to: %v", https)) s.n = negroni.New( NewLogger(), negroni.NewRecovery(), negroni.HandlerFunc(s.authMiddleware), ) s.r = httprouter.New() // Use negroni to handle routes s.n.UseHandler(s.r) return s, nil }
func MakeTestServer(repository matchRepository) *negroni.Negroni { server := negroni.New() // don't need all the middleware here or logging. mx := mux.NewRouter() initRoutes(mx, formatter, repository) server.UseHandler(mx) return server }
func prepareServer(router *mux.Router, globalConfiguration *GlobalConfiguration, oldServer *manners.GracefulServer, middlewares ...negroni.Handler) (*manners.GracefulServer, error) { log.Info("Preparing server") // middlewares var negroni = negroni.New() for _, middleware := range middlewares { negroni.Use(middleware) } negroni.UseHandler(router) tlsConfig, err := createTLSConfig(globalConfiguration.Certificates) if err != nil { log.Fatalf("Error creating TLS config %s", err) return nil, err } if oldServer == nil { return manners.NewWithServer( &http.Server{ Addr: globalConfiguration.Port, Handler: negroni, TLSConfig: tlsConfig, }), nil } server, err := oldServer.HijackListener(&http.Server{ Addr: globalConfiguration.Port, Handler: negroni, TLSConfig: tlsConfig, }, tlsConfig) if err != nil { log.Fatalf("Error hijacking server %s", err) return nil, err } return server, nil }
func NewDispatcher(h ServiceHandler) http.Handler { rp := &Dispatcher{handler: h} t := h.service.Timeout if t <= 0 { t = DEFAULT_TIMEOUT } timeout := time.Duration(t) rp.Transport = &http.Transport{ Dial: timeoutDialer(timeout*time.Second, timeout*time.Second), Proxy: http.ProxyFromEnvironment, TLSHandshakeTimeout: timeout * time.Second, } //Load middlewares before adding the reverse proxy to the stack. n := negroni.New() n.Use(middleware.NewRequestIdMiddleware()) for _, m := range h.middlewares { n.Use(negroni.HandlerFunc(m.ProcessRequest)) } rp.proxy = &ReverseProxy{ Director: rp.Director, Transport: rp, Transformers: h.transformers, } n.UseHandler(rp.proxy) return n }