func (a *Api) Run() error { globalMux := http.NewServeMux() authRouter := mux.NewRouter() authRouter.HandleFunc("/auth/login", a.login).Methods("GET") authRouter.HandleFunc("/auth/logout", a.logout).Methods("GET") authRouter.HandleFunc("/auth/callback", a.authCallback).Methods("GET") apiRouter := mux.NewRouter() apiRouter.Handle("/api/domains", a.authRequiredMiddleware(http.HandlerFunc(a.domains))).Methods("GET") apiRouter.Handle("/api/domains", a.authRequiredMiddleware(http.HandlerFunc(a.addDomain))).Methods("POST") apiRouter.Handle("/api/domains/{prefix:.*}", a.authRequiredMiddleware(http.HandlerFunc(a.removeDomain))).Methods("DELETE") apiRouter.HandleFunc("/api/ip", a.getIP).Methods("GET") //globalMux.Handle("/api/", apiRouter) globalMux.Handle("/api/", apiRouter) globalMux.Handle("/auth/", authRouter) // global handler globalMux.Handle("/", http.FileServer(http.Dir("static"))) s := &http.Server{ Addr: a.listenAddr, Handler: context.ClearHandler(globalMux), } if err := s.ListenAndServe(); err != nil { return err } return http.ListenAndServe(a.listenAddr, context.ClearHandler(globalMux)) }
func main() { flag.Parse() s, err := susigo.NewSusi(*susiaddr, *cert, *key) if err != nil { log.Printf("Error while creating susi connection: %v", err) return } susi = s log.Println("successfully create susi connection") sessionTimeouts = make(map[string]time.Time) if *user == "" && *pass == "" { http.HandleFunc("/publish", publishHandler) http.HandleFunc("/upload", uploadHandler) http.Handle("/ws", websocket.Handler(websocketHandler)) http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir(*assetDir)))) http.HandleFunc("/", redirectToIndex) } else { http.HandleFunc("/publish", BasicAuth(publishHandler)) http.HandleFunc("/upload", BasicAuth(uploadHandler)) http.HandleFunc("/ws", BasicAuth(websocket.Handler(websocketHandler).ServeHTTP)) http.HandleFunc("/assets/", BasicAuth(http.StripPrefix("/assets/", http.FileServer(http.Dir(*assetDir))).ServeHTTP)) http.HandleFunc("/", BasicAuth(redirectToIndex)) } log.Printf("starting http server on %v...", *webaddr) if *useHTTPS { log.Fatal(http.ListenAndServeTLS(*webaddr, *cert, *key, context.ClearHandler(http.DefaultServeMux))) } else { log.Fatal(http.ListenAndServe(*webaddr, context.ClearHandler(http.DefaultServeMux))) } }
func main() { //Setup the logger logger.InitLogger(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr) //Read configuration information from server_config.json config.ReadServerConf() //The port our server listens on listenPort := config.ServerConf.Port logger.Info.Printf("Sever Starting - Listing on port %d - (Version - %s)", listenPort, consts.SERVER_VERSION) //Create router router := mux.NewRouter() //Setup our routes router.Handle("/people", handlers.Execute(&handlers.PeopleHandler{}, handlers.AuthHandlerAdapter(), handlers.DBConnAdapter())).Methods("GET") router.Handle("/places", handlers.Execute(&handlers.PlacesHandler{}, handlers.AuthHandlerAdapter(), handlers.DBConnAdapter())).Methods("GET") //Listen for connections and serve content logger.Info.Println(http.ListenAndServe(":"+strconv.Itoa(listenPort), context.ClearHandler(logger.HttpLog(router)))) }
// Load the web server func Load(c interfaces.Configuration) { log.Debugln("Loading HTTP server") config = c auth.InitStore(config) misc.Init(config) util.Init(config) http.HandleFunc("/history/", misc.History) http.HandleFunc("/script/", misc.Script) http.HandleFunc("/network/", misc.Network) http.HandleFunc("/settings/", misc.Settings) http.HandleFunc("/auth/login", auth.Login) http.HandleFunc("/auth/confirm", auth.EmailConfirm) http.HandleFunc("/auth/password/reset", auth.PasswordReset) http.HandleFunc("/auth/password/forgot", auth.PasswordForgot) http.HandleFunc("/auth/password/change", auth.PasswordChange) http.HandleFunc("/auth/register", auth.Register) http.HandleFunc("/auth/check", auth.HTTPCheck) http.HandleFunc("/socket", socket.Serve) err := http.ListenAndServe(config.GetAddr(), context.ClearHandler(http.DefaultServeMux)) if err != nil { log.Fatalf("Failed to listen to %s: %s", config.GetAddr(), err) log.Parent.Close() os.Exit(4) } }
func main() { globalMux := http.NewServeMux() dockerUrl := "tcp://127.0.0.1:5554" tlsCaCert := "" tlsCert := "" tlsKey := "" allowInsecure := true log.SetLevel(log.DebugLevel) client, err := utils.GetClient(dockerUrl, tlsCaCert, tlsCert, tlsKey, allowInsecure) if err != nil { log.Fatal(err) } a := &Api{client, true, true, &sync.Mutex{}} globalMux.Handle("/", http.FileServer(http.Dir("static"))) globalMux.Handle("/exec", websocket.Handler(a.execContainer)) globalMux.Handle("/ws", websocket.Handler(a.execContainer)) s := &http.Server{ Addr: "0.0.0.0:8081", Handler: context.ClearHandler(globalMux), } var runErr error runErr = s.ListenAndServe() if runErr != nil { log.Fatal(runErr) } }
func main() { //Setup router router := mux.NewRouter() handlers.ConfigUserHandler(router.PathPrefix("/user").Subrouter()) handlers.ConfigFormHandler(router.PathPrefix("/form").Subrouter()) handlers.ConfigMiscHandlers(router.PathPrefix("/misc").Subrouter()) handlers.ConfigReviewHandler(router.PathPrefix("/review").Subrouter()) handlers.ConfigRecommHandler(router.PathPrefix("/recomm").Subrouter()) handlers.ConfigAdminHandler(router.PathPrefix("/gm").Subrouter()) http.Handle("/", router) //Setup CORS Options origins := make([]string, 1) origins[0] = "*" allowOrigins := goHandlers.AllowedOrigins(origins) addrStr := fmt.Sprintf("%s:%d", public.Config.GetString("server.address"), public.Config.GetInt("server.port")) public.LogV.Printf("Listen address: %s\n", addrStr) public.LogE.Fatal(http.ListenAndServe( addrStr, context.ClearHandler(goHandlers.CORS(allowOrigins)(http.DefaultServeMux)), )) }
func startApp(port string) { // Load environment variables envVars := loadEnvVars() // Override with cloud foundry user provided service credentials if specified. loadUPSVars(&envVars) app, settings, err := controllers.InitApp(envVars) if err != nil { // Print the error. fmt.Println(err.Error()) // Terminate the program with a non-zero value number. // Need this for testing purposes. os.Exit(1) } if settings.PProfEnabled { pprof.InitPProfRouter(app) } if envVars.NewRelicLicense != "" { fmt.Println("starting monitoring...") startMonitoring(envVars.NewRelicLicense) } fmt.Println("starting app now...") // TODO add better timeout message. By default it will just say "Timeout" protect := csrf.Protect([]byte(envVars.SessionKey), csrf.Secure(settings.SecureCookies)) http.ListenAndServe(":"+port, protect( http.TimeoutHandler(context.ClearHandler(app), helpers.TimeoutConstant, ""), )) }
func main() { fmt.Println("") fmt.Println("") fmt.Println("-------------------------STARTUP OF SERVER-------------------------") if len(os.Args) < 2 { panic("Cannot startup, the first argument must be the config path") } settings := NewDefaultSettings(os.Args[1]) ctx := RouterContext.New(settings) router := mux.NewRouter() setRouteDefinitions(ctx, router) n := negroni.New(getNegroniHandlers(ctx, router)...) //negroni.Classic() n.UseHandler(context.ClearHandler(router)) ctx.Logger.Info("Now serving on %s", settings.ServerBackendUrl()) backendUrl, err := url.Parse(settings.ServerBackendUrl()) CheckError(err) hostWithPossiblePortOnly := backendUrl.Host if settings.IsDevMode() { graceful.Run(hostWithPossiblePortOnly, 0, n) } else { graceful.Run(hostWithPossiblePortOnly, 5*time.Second, n) //Graceful shutdown to allow 5 seconds to close connections } }
func (cmd *ATCCommand) constructHTTPHandler( webHandler http.Handler, apiHandler http.Handler, oauthHandler http.Handler, ) http.Handler { webMux := http.NewServeMux() webMux.Handle("/api/v1/", apiHandler) webMux.Handle("/auth/", oauthHandler) webMux.Handle("/", webHandler) var httpHandler http.Handler httpHandler = webMux // proxy Authorization header to/from auth cookie, // to support auth from JS (EventSource) and custom JWT auth httpHandler = auth.CookieSetHandler{ Handler: httpHandler, } // don't leak gorilla context per-request httpHandler = context.ClearHandler(httpHandler) return httpHandler }
func main() { var ( confPath string ) flag.StringVar(&confPath, "f", "./ipcapcom.conf", "path to config file") flag.Parse() err := gcfg.ReadFileInto(&cfg, confPath) if err != nil { fmt.Fprintf(os.Stderr, "error reading config file: %v\n", err) os.Exit(1) } r := mux.NewRouter() r.HandleFunc("/ping", handlePing).Methods("GET") r.HandleFunc("/apply", handleApply).Methods("POST") r.HandleFunc("/purge", handlePurge).Methods("GET") r.PathPrefix("/").Handler(http.FileServer(http.Dir(cfg.General.StaticDir))) http.Handle("/", context.ClearHandler(r)) go reaper() err = http.ListenAndServe(":"+cfg.General.ListenPort, nil) if err != nil { fmt.Fprintf(os.Stderr, "error: %v\n", err) os.Exit(1) } }
func main() { flag.Parse() var cfg Config _, err := toml.DecodeFile(*configFilePath, &cfg) if err != nil { log.Fatal("Failed reading config file:", err) } if cfg.Log.Path != "" { lf, err := os.Create(cfg.Log.Path) if err != nil { log.Fatal("Failed opening log file:", err) } log.SetOutput(lf) } if cfg.Server.BaseURL == "" { log.Fatal("Missing required base-url setting") } // CSRF defeat: JSON-only API (reject non-JSON content types) s := http.Server{ Addr: cfg.Server.Bind, Handler: newJsonVerifier(context.ClearHandler(NewProxy(&cfg))), } log.Println("Proxy server listening on", cfg.Server.Bind) err = s.ListenAndServe() if err != nil { log.Fatal(err) } }
func (s *setupStruct) setupRoutes() { commonMids := commonMiddlewares() authMids := authMiddlewares() normal := func(h http.HandlerFunc) httprouter.Handle { return xhttp.Adapt(commonMids(h)) } auth := func(h http.HandlerFunc) httprouter.Handle { return xhttp.Adapt(commonMids(authMids(h))) } router := httprouter.New() itemStore := stores.NewItemStore(s.Rethink) userStore := stores.NewUserStore(s.Rethink) { itemCtrl := handlers.NewItemCtrl(itemStore) router.GET("/v1/item", normal(itemCtrl.List)) router.GET("/v1/item/:id", normal(itemCtrl.Get)) router.POST("/v1/item", auth(itemCtrl.Create)) } { userCtrl := handlers.NewUserCtrl(userStore) router.GET("/v1/user", normal(userCtrl.List)) router.GET("/v1/user/:id", normal(userCtrl.Get)) router.POST("/v1/user", auth(userCtrl.Create)) } s.Handler = context.ClearHandler(router) }
func NewRouter(appContext *ApplicationContext) *mux.Router { opts := &respond.Options{ Before: func(w http.ResponseWriter, r *http.Request, status int, data interface{}) (int, interface{}) { dataEnvelope := map[string]interface{}{"code": status} if err, ok := data.(error); ok { dataEnvelope["error"] = err.Error() dataEnvelope["success"] = false } else { dataEnvelope["data"] = data dataEnvelope["success"] = true } return status, dataEnvelope }, } router := mux.NewRouter() for _, route := range routes { var handler http.Handler handler = opts.Handler(route.Handler) handler = CORSHandler(ContextAwareHandler(handler, appContext), route) handler = context.ClearHandler(handler) router. Methods([]string{route.Method, "OPTIONS"}...). Path(route.Pattern). Name(route.Name). Handler(handler) } return router }
func TestNewSession(t *testing.T) { store := sessions.NewCookieStore([]byte("secret")) fn := func(c web.C, w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok")) } mux := web.New() mux.Handle("/*", fn) mux.Use(Middleware("session", store)) ts := httptest.NewServer(context.ClearHandler(mux)) defer ts.Close() var err error var resp *http.Response resp, err = http.Get(ts.URL) if err != nil { t.Fatal(err) } cookie := resp.Header.Get("Set-Cookie") t.Logf("Set-Cookie: %v", cookie) if cookie == "" { t.Fatal("\"Set-Cookie\" header missing") } matches := sessionPattern.FindStringSubmatch(cookie) if len(matches) != 2 { t.Fatal("session cookie missing") } }
func registerRoutes() http.Handler { h := http.NewServeMux() mux := pat.New() // register routes mux.Get("/", http.HandlerFunc(root)) mux.Get("/upload", oauthWrapper(http.HandlerFunc(uploadPage))) mux.Post("/upload", oauthWrapper(http.HandlerFunc(uploadHandler))) mux.Get("/auth", http.HandlerFunc(oauthRedirectHandler)) mux.Get("/search", http.HandlerFunc(searchPage)) mux.Get("/image/:hash", http.HandlerFunc(imagePage)) mux.Get("/:hash", http.HandlerFunc(getImageHandler)) mux.Get("/:hash/:width", http.HandlerFunc(getImageHandlerWidth)) mux.Get("/", http.HandlerFunc(root)) h.Handle("/", loggerMiddlerware(mux)) h.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/")))) // load templates templates = loadTemplates() return context.ClearHandler(h) }
// rProxy is a single host reverse proxy implementation // See github.com/peteretelej/rproxy func rProxy(listenAddr, remoteHost, scheme string) { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { session, err := store.Get(r, "sess") if err != nil { // compromised cookie? http.Error(w, err.Error(), 500) return } var allow, resetsess bool var wait string sid, exists := session.Values["sessid"] if exists { if val, ok := sid.(int); ok { allow, err = isAllowed(val) if err != nil { // not allowed and not waiting delete(session.Values, "sessid") resetsess = true } else { if !allow { // client already waiting, get wait time wait = getWait(val) } } } else { http.Error(w, "User SessionID not int", 500) return } } else { // No session ID exists (new user) resetsess = true } // Reset user session, either new user or // User with and retired session if resetsess { id, allowed := handleNew() session.Values["sessid"] = id allow = allowed if !allowed { // get wait time if new session was set to wait wait = getWait(id) } } session.Save(r, w) // Handle waiting user, notify when they can access if !allow { w.Write([]byte("Please try again later at: " + wait)) return } p := httputil.NewSingleHostReverseProxy(&url.URL{ Scheme: scheme, Host: remoteHost, }) p.ServeHTTP(w, r) }) log.Fatal(http.ListenAndServe(listenAddr, context.ClearHandler(http.DefaultServeMux))) }
func NewServer(conf *ServerConf) *server { if conf.Name == "" { conf.Name = "server" } if conf.Port == 0 { conf.Port = DEFAULT_PORT } if conf.SessionSecret == "" { conf.SessionSecret = DEFAULT_SESSION_SECRET } self := &server{conf: conf} self.serverMux = http.NewServeMux() self.server = &graceful.Server{ Timeout: 500 * time.Millisecond, Server: &http.Server{ Addr: ":" + self.getPortStr(), Handler: self.LogMiddleware(context.ClearHandler(self.serverMux)), }, } self.server.SetKeepAlivesEnabled(false) // FIXME self.cookieStore = sessions.NewCookieStore([]byte(self.conf.SessionSecret)) self.setupHandlers() fs := http.FileServer(http.Dir(self.conf.StaticDir)) self.serverMux.Handle(self.conf.StaticUrl, http.StripPrefix("", fs)) self.setupLogging() self.genPaths = make(map[string]*genpath.GenPath) return self }
func (cfg *Config) Handler(h http.Handler) http.Handler { cfg.mustInit() // TODO: nonce? csp := "default-src 'self' https://www.google-analytics.com; frame-ancestors 'none'; img-src 'self' https://www.google-analytics.com data:; form-action 'self'; plugin-types;" if reportURI.Value() != "" { csp += fmt.Sprintf(" report-uri %s;", reportURI.Value()) } var h2 http.Handler = http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { cRequestsHandled.Inc() miscctx.SetResponseWriter(rw, req) context.Set(req, &ServerKey, cfg.Server) hdr := rw.Header() hdr.Set("X-Frame-Options", "DENY") hdr.Set("X-Content-Type-Options", "nosniff") hdr.Set("X-UA-Compatible", "ie=edge") hdr.Set("Content-Security-Policy", csp) if origin.IsSSL(req) { hdr.Set("Strict-Transport-Security", "max-age=15552000") } if !opts.DevMode && !cfg.NoForceSSL && !origin.IsSSL(req) { cfg.redirectHTTPS(rw, req) return } if cfg.StripWWW && strings.HasPrefix(req.Host, "www.") { cfg.redirectStripWWW(rw, req) return } h.ServeHTTP(rw, req) }) if cfg.SessionConfig != nil { h2 = cfg.SessionConfig.InitHandler(h2) } if cfg.CAPTCHA == nil { cfg.CAPTCHA = &captcha.Config{ DisallowHandlerNew: true, Leeway: 1, } if captchaFontPathFlag.Value() != "" { cfg.CAPTCHA.SetFontPath(captchaFontPathFlag.Value()) } } mux := http.NewServeMux() mux.Handle("/", h2) mux.Handle("/.captcha/", cfg.CAPTCHA.Handler("/.captcha/")) mux.Handle("/.csp-report", cspreport.Handler) mux.Handle("/.service-nexus/", servicenexus.Handler(h2)) return context.ClearHandler(timingHandler(errorhandler.Handler(methodOverride(mux)))) }
func main() { flag.Parse() k := new(Kasse) k.log = log.New(os.Stderr, "", log.LstdFlags) if db, err := sqlx.Connect(*driver, *connect); err != nil { log.Fatal("Could not open database:", err) } else { k.db = db } defer func() { if err := k.db.Close(); err != nil { log.Println("Error closing database:", err) } }() k.sessions = sessions.NewCookieStore([]byte("TODO: Set up safer password")) http.Handle("/", handlers.LoggingHandler(os.Stderr, k.Handler())) var lcd *lcd2usb.Device if *hardware { var err error if lcd, err = lcd2usb.Open("/dev/ttyACM0", 2, 16); err != nil { log.Fatal(err) } } events := make(chan NFCEvent) // We have to wrap the call in a func(), because the go statement evaluates // it's arguments in the current goroutine, and the argument to log.Fatal // blocks in these cases. if *hardware { go func() { log.Fatal(ConnectAndPollNFCReader("", events)) }() } RegisterHTTPReader(k) go func() { log.Fatal(http.ListenAndServe(*listen, context.ClearHandler(http.DefaultServeMux))) }() for { ev := <-events if ev.Err != nil { log.Println(ev.Err) continue } res, err := k.HandleCard(ev.UID) if res != nil { res.Print(lcd) } else { // TODO: Distinguish between user-facing errors and internal errors flashLCD(lcd, err.Error(), 255, 0, 0) } } }
func main() { http.HandleFunc("/", index) http.HandleFunc("/login", login) http.HandleFunc("/logout", logout) http.Handle("/assets/imgs/", http.StripPrefix("/assets/imgs", http.FileServer(http.Dir("./assets/imgs")))) http.Handle("/favicon.ico", http.NotFoundHandler()) http.ListenAndServe(":8080", context.ClearHandler(http.DefaultServeMux)) }
func ListenAndServe(listenAddr string, dockerAddr string) error { mainMux := http.NewServeMux() mainMux.Handle("/", http.FileServer(http.Dir("web/static"))) api.RegisterRoutes(mainMux, dockerAddr) return http.ListenAndServe(listenAddr, context.ClearHandler(mainMux)) }
// Load the web server func Load(addr string) { http.HandleFunc("/create", create) http.HandleFunc("/socket", serveWs) err := http.ListenAndServe(addr, context.ClearHandler(http.DefaultServeMux)) if err != nil { panic(err) } }
func Router() http.Handler { router := mux.NewRouter().StrictSlash(true) router.HandleFunc("/", IndexHandler) router.NotFoundHandler = http.HandlerFunc(NotFoundHandler) return context.ClearHandler(Interceptor(CorsSupport(router))) }
func main() { http.HandleFunc("/", home) http.HandleFunc("/admin", admin) http.HandleFunc("/admin/upload", upload) http.HandleFunc("/admin/logout", logout) http.Handle("/imgs/", http.StripPrefix("/imgs/", http.FileServer(http.Dir("imgs/")))) http.ListenAndServe(":9000", context.ClearHandler(http.DefaultServeMux)) }
func main() { flag.Parse() if *generateConfig { if _, err := os.Stat("config.json"); os.IsNotExist(err) { log.Println("Generating config...") ioutil.WriteFile("config.json", []byte(`{ "host_and_port":":1234", "webroot":"webroot", "root_title":"An Editable Site", "redis_host_and_port":"localhost:6379", "process_command":"./process.sh" } `), 0600) } else { log.Println("Config file 'config.json' already exists - we will not overwrite it.") } os.Exit(0) } getConfig() tmpDuration, _ := time.ParseDuration("8h") pageLockTTL = tmpDuration.Seconds() err := os.Mkdir(config.Webroot, 0700) if os.IsPermission(err) { panic(fmt.Sprintf("Unable to create required webroot directory: '%s'", config.Webroot)) } pool = newPool() _, err = rdo("PING") if err != nil { panic(fmt.Sprintf("A working connection to a Redis instance is required: %s - You may need to tweak the config.go file prior to building.", err)) } if exists, err := redis.Bool(rdo("EXISTS", "USER:admin")); err == nil && !exists { log.Println("Creating default admin account, since it doesn't currently exist. ('admin'/'password')") bp, err := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost) if err != nil { panic(fmt.Sprintf("Unable to generate bcrypt from password to create admin account: %s", err)) } rdo("SET", "USER:admin", bp) rdo("SET", "root", "admin") rdo("SADD", "ADMINS", "admin") } http.HandleFunc("/", h) http.HandleFunc("/dl", dl) http.HandleFunc("/toc", t) http.HandleFunc("/admin", a) http.HandleFunc("/admin/remove", r) http.HandleFunc("/user", u) http.HandleFunc("/file/", f) http.HandleFunc("/lock", l) http.HandleFunc("/unlock", ul) http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {}) log.Println("Listening on " + config.HostAndPort) /* tlsConfig := &tls.Config{MinVersion: tls.VersionTLS10} server := &http.Server{Addr: config.HostAndPort, Handler: authd(http.DefaultServeMux), TLSConfig: tlsConfig} log.Fatal(server.ListenAndServeTLS("cert.pem", "key.pem")) */ log.Fatal(http.ListenAndServeTLS(config.HostAndPort, "cert.pem", "key.pem", context.ClearHandler(authd(http.DefaultServeMux)))) }
func init() { serveMux := http.NewServeMux() serveMux.HandleFunc("/", handleIndex) http.Handle("/", context.ClearHandler(serveMux)) //http.ListenAndServe(":8080", context.ClearHandler(http.DefaultServeMux)) }
func middleware(h http.Handler) http.Handler { // Log every request h = logrequest.Database(h) // Clear handler for Gorilla Context h = context.ClearHandler(h) return h }
func main() { http.HandleFunc("/auth", credentialHandler) http.HandleFunc("/email", emailHandler) http.HandleFunc("/upload", uploadHandler) //static file handler. http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets")))) //Listen on port 8080 http.ListenAndServe(":8080", context.ClearHandler(http.DefaultServeMux)) }
func init() { app := negroni.Classic() // store := sessions.NewCookieStore([]byte("something-very-secret")) // app.Use(sessionauth.SessionUser(store, "rs_sess", GenerateAnonymousUser)) app.UseHandler(makeRoutes()) http.Handle("/", context.ClearHandler(app)) }
func createAndRegisterRoutersHandler(ctx *RouterContext) http.Handler { mainRouter := mux.NewRouter().StrictSlash(true) setupApiV1Routes(ctx, mainRouter) mainRouter.NotFoundHandler = ¬FoundHandler{ctx} n := negroni.New(getNegroniHandlers(ctx, mainRouter)...) n.UseHandler(context.ClearHandler(mainRouter)) return n }