func InitStaticRouter(staticDir, staticETag string, mgr *cbgt.Manager) *mux.Router { prefix := "" if mgr != nil { prefix = mgr.Options()["urlPrefix"] } hfsStaticX := http.FileServer(assetFS()) router := mux.NewRouter() router.StrictSlash(true) router.Handle(prefix+"/", http.RedirectHandler(prefix+"/index.html", 302)) router.Handle(prefix+"/index.html", http.RedirectHandler(prefix+"/staticx/index.html", 302)) router.Handle(prefix+"/static/partials/index/start.html", http.RedirectHandler(prefix+"/staticx/partials/index/start.html", 302)) router = rest.InitStaticRouterEx(router, staticDir, staticETag, []string{ prefix + "/indexes", prefix + "/nodes", prefix + "/monitor", prefix + "/manage", prefix + "/logs", prefix + "/debug", }, http.RedirectHandler(prefix+"/staticx/index.html", 302), mgr) router.PathPrefix(prefix + "/staticx/").Handler( http.StripPrefix(prefix+"/staticx/", hfsStaticX)) return router }
func main() { mux := http.NewServeMux() fileServer := http.FileServer(http.Dir("assets")) mux.Handle("/nav/http-csp.html", cspNoReferrer(fileServer)) mux.Handle("/img/http-csp.html", cspNoReferrer(fileServer)) mux.Handle("/redirect/http-refresh", httpRefresher("../echo.txt")) mux.Handle("/redirect/301.png", http.RedirectHandler("/echo.png", 301)) mux.Handle("/redirect/301.txt", http.RedirectHandler("/echo.txt", 301)) mux.Handle("/echo.txt", cacheControl(http.HandlerFunc(echoText))) mux.Handle("/echo.png", cacheControl(http.HandlerFunc(echoImage))) mux.Handle("/", fileServer) go http.ListenAndServeTLS(":1443", "tls.crt", "tls.key", mux) fmt.Println("Listening at https://localhost:1443") sig := make(chan os.Signal, 1) signal.Notify(sig, os.Interrupt) <-sig fmt.Println("") }
func urlMap(e *Env) { // http.HandleFunc("/auth/logout", authLogout()) // redirect //http.Handle("/some/path/robots.txt", http.RedirectHandler("/robots.txt", http.StatusMovedPermanently)) if FacebookLoginURL() != "" { http.Handle("/login/facebook", Handler{e, HandleFacebookLogin}) http.Handle("/callback/facebook", LoginHandler{e, HandleFacebookCallback}) } if GooglePlusLoginURL() != "" { http.Handle("/login/google", Handler{e, HandleGooglePlusLogin}) http.Handle("/callback/google", LoginHandler{e, HandleGooglePlusCallback}) } http.Handle("/logout", Handler{e, HandleLogout}) http.Handle("/robots.txt", http.RedirectHandler("/static/robots.txt", http.StatusMovedPermanently)) http.Handle("/favicon.ico", http.RedirectHandler("/static/favicon.ico", http.StatusMovedPermanently)) // Pages http.Handle("/albums/", Handler{e, albumsHandler}) // Normal resources http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("public")))) // http.HandleFunc("/albums/", requestAlbum()) http.Handle("/", Handler{e, rootHandler}) }
func main() { http.HandleFunc("/", renderTemplate("index.html")) http.HandleFunc("/sprites", renderTemplate("sprites.html")) http.HandleFunc("/soundtrack/disc/1", renderTemplate("disc1.html")) http.HandleFunc("/soundtrack/disc/2", renderTemplate("disc2.html")) http.HandleFunc("/downloads/hawkthorne-win-x64.zip", trackDownload("hawkthorne-win-x64.zip")) http.HandleFunc("/downloads/hawkthorne-win-x86.zip", trackDownload("hawkthorne-win-x86.zip")) http.HandleFunc("/downloads/hawkthorne-osx.zip", trackDownload("hawkthrone-osx.zip")) http.HandleFunc("/downloads/hawkthorne.love", trackDownload("hawkthorne.love")) http.Handle("/sprites.html", http.RedirectHandler("/sprites", 301)) http.Handle("/audio.html", http.RedirectHandler("/soundtrack/disc/1", 301)) http.Handle("/soundtrack.html", http.RedirectHandler("/soundtrack/disc/1", 301)) http.Handle("/soundtrack-disc2.html", http.RedirectHandler("/soundtrack/disc/2", 301)) port := os.Getenv("PORT") if port == "" { port = "8080" } pfx := "/static/" h := http.StripPrefix(pfx, http.FileServer(http.Dir("static"))) http.Handle(pfx, h) log.Fatal(http.ListenAndServe(":"+port, nil)) }
func InitStaticRouter(staticDir, staticETag string) *mux.Router { hfsStaticX := http.FileServer(assetFS()) router := mux.NewRouter() router.StrictSlash(true) router.Handle("/", http.RedirectHandler("/staticx/index.html", 302)) router.Handle("/index.html", http.RedirectHandler("/staticx/index.html", 302)) router.Handle("/static/partials/index/list.html", http.RedirectHandler("/staticx/partials/index/list.html", 302)) router = rest.InitStaticRouter(router, staticDir, staticETag, []string{ "/indexes", "/nodes", "/monitor", "/manage", "/logs", "/debug", }, http.RedirectHandler("/staticx/index.html", 302)) router.PathPrefix("/staticx/").Handler( http.StripPrefix("/staticx/", hfsStaticX)) return router }
// Creates a GorillaMux router containing the HTTP handlers for a server. func createHandler(sc *serverContext) http.Handler { r := mux.NewRouter() r.StrictSlash(true) // Global operations: r.Handle("/", makeHandler(sc, (*handler).handleRoot)).Methods("GET", "HEAD") r.Handle("/_all_dbs", makeHandler(sc, (*handler).handleAllDbs)).Methods("GET", "HEAD") if len(sc.databases) == 1 { // If there is exactly one database we can handle the standard /_session by just redirecting // it to that database's _session handler. for _, db := range sc.databases { path := "/" + db.dbcontext.Name r.Handle("/_session", http.RedirectHandler(path+"/_session", http.StatusTemporaryRedirect)) r.Handle("/_persona", http.RedirectHandler(path+"/_persona", http.StatusTemporaryRedirect)) } } else { r.Handle("/_session", http.NotFoundHandler()) r.Handle("/_persona", http.NotFoundHandler()) } // Operations on databases: r.Handle("/{newdb}/", makeHandler(sc, (*handler).handleCreateDB)).Methods("PUT") r.Handle("/{db}/", makeHandler(sc, (*handler).handleGetDB)).Methods("GET", "HEAD") r.Handle("/{db}/", makeHandler(sc, (*handler).handleDeleteDB)).Methods("DELETE") r.Handle("/{db}/", makeHandler(sc, (*handler).handlePostDoc)).Methods("POST") // Special database URLs: dbr := r.PathPrefix("/{db}/").Subrouter() dbr.Handle("/_all_docs", makeHandler(sc, (*handler).handleAllDocs)).Methods("GET", "HEAD", "POST") dbr.Handle("/_bulk_docs", makeHandler(sc, (*handler).handleBulkDocs)).Methods("POST") dbr.Handle("/_bulk_get", makeHandler(sc, (*handler).handleBulkGet)).Methods("GET", "HEAD") dbr.Handle("/_changes", makeHandler(sc, (*handler).handleChanges)).Methods("GET", "HEAD") dbr.Handle("/_design/sync_gateway", makeHandler(sc, (*handler).handleDesign)).Methods("GET", "HEAD") dbr.Handle("/_ensure_full_commit", makeHandler(sc, (*handler).handleEFC)).Methods("POST") dbr.Handle("/_revs_diff", makeHandler(sc, (*handler).handleRevsDiff)).Methods("POST") // Session/login URLs are per-database (unlike in CouchDB) dbr.Handle("/_session", makeAdminHandler(sc, (*handler).handleSessionGET)).Methods("GET", "HEAD") dbr.Handle("/_session", makeAdminHandler(sc, (*handler).handleSessionPOST)).Methods("POST") if sc.config.Persona != nil { dbr.Handle("/_persona", makeAdminHandler(sc, (*handler).handlePersonaPOST)).Methods("POST") } // Document URLs: dbr.Handle("/_local/{docid}", makeHandler(sc, (*handler).handleGetLocalDoc)).Methods("GET", "HEAD") dbr.Handle("/_local/{docid}", makeHandler(sc, (*handler).handlePutLocalDoc)).Methods("PUT") dbr.Handle("/_local/{docid}", makeHandler(sc, (*handler).handleDelLocalDoc)).Methods("DELETE") dbr.Handle("/{docid}", makeHandler(sc, (*handler).handleGetDoc)).Methods("GET", "HEAD") dbr.Handle("/{docid}", makeHandler(sc, (*handler).handlePutDoc)).Methods("PUT") dbr.Handle("/{docid}", makeHandler(sc, (*handler).handleDeleteDoc)).Methods("DELETE") dbr.Handle("/{docid}/{attach}", makeHandler(sc, (*handler).handleGetAttachment)).Methods("GET", "HEAD") // Fallbacks that have to be added last: r.PathPrefix("/").Methods("OPTIONS").Handler(makeHandler(sc, (*handler).handleOptions)) r.PathPrefix("/").Handler(makeHandler(sc, (*handler).handleBadRoute)) return r }
func init() { http.HandleFunc("/assets/", assetsHandler) http.HandleFunc("/page/", pageHandler) http.HandleFunc("/_jt/cron/updateCounts", updateCountsHandler) http.HandleFunc("/", notFoundHandler) http.Handle("/resume.pdf", http.RedirectHandler(cdnUrl+"/assets/pdf/resume.pdf", http.StatusTemporaryRedirect)) http.Handle("/resume.tex", http.RedirectHandler(cdnUrl+"/assets/pdf/resume.tex", http.StatusTemporaryRedirect)) }
func main() { // Add routes to the global handler goji.Get("/", Root) // Fully backwards compatible with net/http's Handlers goji.Get("/greets", http.RedirectHandler("/", 301)) // Use your favorite HTTP verbs goji.Post("/greets", NewGreet) // Use Sinatra-style patterns in your URLs goji.Get("/users/:name", GetUser) // Goji also supports regular expressions with named capture groups. goji.Get(regexp.MustCompile(`^/greets/(?P<id>\d+)$`), GetGreet) // Middleware can be used to inject behavior into your app. The // middleware for this application are defined in middleware.go, but you // can put them wherever you like. goji.Use(PlainText) // If the patterns ends with "/*", the path is treated as a prefix, and // can be used to implement sub-routes. admin := web.New() goji.Handle("/admin/*", admin) // The standard SubRouter middleware helps make writing sub-routers // easy. Ordinarily, Goji does not manipulate the request's URL.Path, // meaning you'd have to repeat "/admin/" in each of the following // routes. This middleware allows you to cut down on the repetition by // eliminating the shared, already-matched prefix. admin.Use(middleware.SubRouter) // You can also easily attach extra middleware to sub-routers that are // not present on the parent router. This one, for instance, presents a // password prompt to users of the admin endpoints. admin.Use(SuperSecure) admin.Get("/", AdminRoot) admin.Get("/finances", AdminFinances) // Goji's routing, like Sinatra's, is exact: no effort is made to // normalize trailing slashes. goji.Get("/admin", http.RedirectHandler("/admin/", 301)) // Use a custom 404 handler goji.NotFound(NotFound) // Sometimes requests take a long time. goji.Get("/waitforit", WaitForIt) // Call Serve() at the bottom of your main() function, and it'll take // care of everything else for you, including binding to a socket (with // automatic support for systemd and Einhorn) and supporting graceful // shutdown on SIGINT. Serve() is appropriate for both development and // production. goji.Serve() }
func main() { goji.Get("/", http.RedirectHandler("/list/1", http.StatusMovedPermanently)) goji.Get("/assets/bestxkcd.css", cssHandler) goji.Get("/list", http.RedirectHandler("/list/1", http.StatusMovedPermanently)) goji.Get("/list/", http.RedirectHandler("/list/1", http.StatusMovedPermanently)) goji.Get("/list/:page", listHandler) goji.Get("/vote", newVoteHandler) goji.Get("/vote/", http.RedirectHandler("/vote", http.StatusMovedPermanently)) goji.Get("/vote/:token", voteHandler) goji.Serve() }
func init() { api := Router.PathPrefix("/api").Subrouter() api.Path("/jobs").Methods("GET").Handler(http.RedirectHandler("jobs/", http.StatusMovedPermanently)) api.Path("/jobs/").Methods("GET").HandlerFunc(jobsIndexHandler) api.Path("/jobs/").Methods("POST").HandlerFunc(jobCreateHandler) api.Path("/jobs/{job}").Methods("GET").HandlerFunc(jobGetHandler) api.Path("/jobs/{job}/builds").Methods("GET").Handler(http.RedirectHandler("builds/", http.StatusMovedPermanently)) api.Path("/jobs/{job}/builds/").Methods("GET").HandlerFunc(buildsIndexHandler) api.Path("/jobs/{job}/builds/").Methods("POST").HandlerFunc(buildCreateHandler) // api.Path("/jobs/{job}/builds/{build}").Methods("GET").HandlerFunc(buildGetHandler) }
func main() { // gtk.Init(&os.Args) // builder := gtk.Builder() // builder.AddFromFile(locateUiFile()) // builder.ConnectSignals(nil) // ui.Init(builder) http.RedirectHandler(url, code) http.Handler("/", http.RedirectHandler("/edit", 301)) http.HandleFunc("/edit", handleEdit) http.HandleFunc("/send", handleSend) http.ListenAndServe(":8080", nil) }
// InitStaticRouterEx is like InitStaticRouter, but with optional // manager parameter for more options. func InitStaticRouterEx(r *mux.Router, staticDir, staticETag string, pages []string, pagesHandler http.Handler, mgr *cbgt.Manager) *mux.Router { prefix := "" if mgr != nil { prefix = mgr.Options()["urlPrefix"] } PIndexTypesInitRouter(r, "static.before", mgr) var s http.FileSystem if staticDir != "" { if _, err := os.Stat(staticDir); err == nil { log.Printf("http: serving assets from staticDir: %s", staticDir) s = http.Dir(staticDir) } } if s == nil { log.Printf("http: serving assets from embedded data") s = AssetFS() } r.PathPrefix(prefix + "/static/").Handler( http.StripPrefix(prefix+"/static/", ETagFileHandler{http.FileServer(s), staticETag})) // Bootstrap UI insists on loading templates from this path. r.PathPrefix(prefix + "/template/").Handler( http.StripPrefix(prefix+"/template/", ETagFileHandler{http.FileServer(s), staticETag})) // If client ask for any of the pages, redirect. for _, p := range pages { if pagesHandler != nil { r.PathPrefix(p).Handler(pagesHandler) } else { r.PathPrefix(p).Handler(RewriteURL("/", http.FileServer(s))) } } r.Handle(prefix+"/index.html", http.RedirectHandler(prefix+"/static/index.html", 302)) r.Handle(prefix+"/", http.RedirectHandler(prefix+"/static/index.html", 302)) PIndexTypesInitRouter(r, "static.after", mgr) return r }
func main() { // Handle debugging if debug || os.Getenv("DEBUG") == "true" { debug = true // Just in case debugOut = log.New(os.Stdout, "[DEBUG]", log.Lshortfile) } debugOut.Printf("Pre-Config:\n%+v\n", GlobalConfig.Map()) // Load Configs if configFolder != "" { loadConfigs(configFolder) } else if cf := os.Getenv("CONFIGFOLDER"); cf != "" { loadConfigs(cf) } debugOut.Printf("Post-Config\n%+v\n", GlobalConfig.Map()) // Setup AWS stuff initAWS() // Goji!!! if GlobalConfig.IsNotNull("serverHeader") { headerString := GlobalConfig.Get("serverHeader") if headerString != "yes" { FULLVERSION = headerString } goji.Use(ServerHeader) } goji.Get("/", http.RedirectHandler(GlobalConfig.Get("formURL"), 301)) goji.Get("/health", healthHandler) goji.Post("/upload", uploadHandler) goji.Get("/upload", http.RedirectHandler(GlobalConfig.Get("getRedirect"), 301)) // Allow handling of static content for webform, thank you page, etc. if GlobalConfig.IsNotNull("staticPath") && GlobalConfig.IsNotNull("staticURL") { debugOut.Printf("Static handling of '%s' mapped to '%s'\n", GlobalConfig.Get("staticURL"), GlobalConfig.Get("staticPath")) goji.Handle(GlobalConfig.Get("staticURL"), http.StripPrefix(strings.TrimRight(GlobalConfig.Get("staticURL"), "*"), http.FileServer(http.Dir(GlobalConfig.Get("staticPath"))))) } goji.Handle("/*", defaultHandler) goji.Serve() }
func RegisterHandlers(mux httpMux.Mux, containerManager manager.Manager, httpAuthFile, httpAuthRealm, httpDigestFile, httpDigestRealm, prometheusEndpoint string) error { // Basic health handler. if err := healthz.RegisterHandler(mux); err != nil { return fmt.Errorf("failed to register healthz handler: %s", err) } // Validation/Debug handler. mux.HandleFunc(validate.ValidatePage, func(w http.ResponseWriter, r *http.Request) { err := validate.HandleRequest(w, containerManager) if err != nil { fmt.Fprintf(w, "%s", err) } }) // Register API handler. if err := api.RegisterHandlers(mux, containerManager); err != nil { return fmt.Errorf("failed to register API handlers: %s", err) } // Redirect / to containers page. mux.Handle("/", http.RedirectHandler(pages.ContainersPage, http.StatusTemporaryRedirect)) var authenticated bool = false // Setup the authenticator object if httpAuthFile != "" { glog.Infof("Using auth file %s", httpAuthFile) secrets := auth.HtpasswdFileProvider(httpAuthFile) authenticator := auth.NewBasicAuthenticator(httpAuthRealm, secrets) mux.HandleFunc(static.StaticResource, authenticator.Wrap(staticHandler)) if err := pages.RegisterHandlersBasic(mux, containerManager, authenticator); err != nil { return fmt.Errorf("failed to register pages auth handlers: %s", err) } authenticated = true } if httpAuthFile == "" && httpDigestFile != "" { glog.Infof("Using digest file %s", httpDigestFile) secrets := auth.HtdigestFileProvider(httpDigestFile) authenticator := auth.NewDigestAuthenticator(httpDigestRealm, secrets) mux.HandleFunc(static.StaticResource, authenticator.Wrap(staticHandler)) if err := pages.RegisterHandlersDigest(mux, containerManager, authenticator); err != nil { return fmt.Errorf("failed to register pages digest handlers: %s", err) } authenticated = true } // Change handler based on authenticator initalization if !authenticated { mux.HandleFunc(static.StaticResource, staticHandlerNoAuth) if err := pages.RegisterHandlersBasic(mux, containerManager, nil); err != nil { return fmt.Errorf("failed to register pages handlers: %s", err) } } collector := metrics.NewPrometheusCollector(containerManager) prometheus.MustRegister(collector) http.Handle(prometheusEndpoint, prometheus.Handler()) return nil }
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) }
func main() { handleWithPrefix("/view/", viewHandler) handleWithPrefix("/edit/", editHandler) handleWithPrefix("/save/", saveHandler) http.Handle("/", http.RedirectHandler("/view/FrontPage", http.StatusFound)) http.ListenAndServe(":80", nil) }
func main() { flag.Parse() client, err := couchbase.Connect(*cbServer) if err != nil { log.Fatalf("Error connecting to couchbase: %v", err) } dataSourceManager, err = datasource.NewCouchbaseDataSourceManager(client) unqlParser = parser.NewUnqlParser() planner = plan.NewCouchbasePlanner(dataSourceManager) optimizer = NewCouchbaseOptimizer() executor = NewCouchbaseExecutor() if *debugParsing { parser.DebugTokens = true parser.DebugGrammar = true } r := mux.NewRouter() // static r.PathPrefix(STATIC_PREFIX).Handler( http.StripPrefix(STATIC_PREFIX, http.FileServer(http.Dir(*staticPath)))) // api r.HandleFunc("/api", welcome).Methods("GET") r.Handle("/api/{bucket}/_query_ast", http.HandlerFunc(bucketQueryAST)).Methods("POST") r.Handle("/api/{bucket}/_query", http.HandlerFunc(bucketQuery)).Methods("GET", "POST") r.Handle("/", http.RedirectHandler("/_static/index.html", 302)) log.Printf("listening rest on: %v", *addr) log.Fatal(http.ListenAndServe(*addr, r)) }
func (a *AgentCommand) ServeHTTP() { r := mux.NewRouter().StrictSlash(true) a.apiRoutes(r) a.dashboardRoutes(r) middle := interpose.New() middle.Use(metaMiddleware(a.config.NodeName)) middle.UseHandler(r) r.Handle("/debug/vars", http.DefaultServeMux) r.PathPrefix("/dashboard").Handler( http.StripPrefix("/dashboard", http.FileServer( http.Dir(filepath.Join(a.config.UIDir, "static"))))) r.PathPrefix("/").Handler(http.RedirectHandler("/dashboard", 301)) srv := &http.Server{Addr: a.config.HTTPAddr, Handler: middle} log.WithFields(logrus.Fields{ "address": a.config.HTTPAddr, }).Info("api: Running HTTP server") certFile := "" //config.GetString("certFile") keyFile := "" //config.GetString("keyFile") if certFile != "" && keyFile != "" { go srv.ListenAndServeTLS(certFile, keyFile) } else { go srv.ListenAndServe() } }
func main() { flag.Parse() storageDriver, err := NewStorageDriver(*argDbDriver) if err != nil { glog.Fatalf("Failed to connect to database: %s", err) } containerManager, err := manager.New(storageDriver) if err != nil { glog.Fatalf("Failed to create a Container Manager: %s", err) } // Register Docker. if err := docker.Register(containerManager); err != nil { glog.Errorf("Docker registration failed: %v.", err) } // Register the raw driver. if err := raw.Register(containerManager); err != nil { glog.Fatalf("raw registration failed: %v.", err) } // Handler for static content. http.HandleFunc(static.StaticResource, func(w http.ResponseWriter, r *http.Request) { err := static.HandleRequest(w, r.URL) if err != nil { fmt.Fprintf(w, "%s", err) } }) // Register API handler. if err := api.RegisterHandlers(containerManager); err != nil { glog.Fatalf("failed to register API handlers: %s", err) } // Redirect / to containers page. http.Handle("/", http.RedirectHandler(pages.ContainersPage, http.StatusTemporaryRedirect)) // Register the handler for the containers page. http.HandleFunc(pages.ContainersPage, func(w http.ResponseWriter, r *http.Request) { err := pages.ServerContainersPage(containerManager, w, r.URL) if err != nil { fmt.Fprintf(w, "%s", err) } }) defer glog.Flush() go func() { glog.Fatal(containerManager.Start()) }() glog.Infof("Starting cAdvisor version: %q", info.VERSION) glog.Infof("About to serve on port ", *argPort) addr := fmt.Sprintf(":%v", *argPort) glog.Fatal(http.ListenAndServe(addr, nil)) }
func init() { r := mux.NewRouter() apiGet := r.PathPrefix("/api").Methods("GET").Subrouter() apiGet.HandleFunc("/{view}", apiController.ApiGetHandler) apiGet.HandleFunc("/{view}/{key}", apiController.ApiGetHandler) apiGet.HandleFunc("/{view}/{parent}/{key}", apiController.ApiGetHandler) apiPost := r.PathPrefix("/api").Methods("POST").Subrouter() apiPost.HandleFunc("/{view}", apiController.ApiPostHandler) apiPost.HandleFunc("/{view}/{key}", apiController.ApiPostHandler) apiDelete := r.PathPrefix("/api").Methods("DELETE").Subrouter() apiDelete.HandleFunc("/{view}/{key}", apiController.ApiDeleteHandler) r.PathPrefix("/admin/").Handler(http.StripPrefix("/admin/", http.FileServer(http.Dir("./static/admin")))) r.PathPrefix("/admin").Handler(http.RedirectHandler("/admin/", 301)) r.PathPrefix("/blog").Handler(http.StripPrefix("/blog", http.FileServer(http.Dir("./static")))) r.PathPrefix("/foundation/").Handler(http.StripPrefix("/foundation/", http.FileServer(http.Dir("./static/foundation")))) r.HandleFunc("/{.path:.*}", cloudAdminHandler).Methods("GET") r.HandleFunc("/{.path:.*}", cloudAdminPostHandler).Methods("POST") http.Handle("/", r) }
func handlerLoadRegexp(rw http.ResponseWriter, req *http.Request) { ctx := appengine.NewContext(req) key := req.URL.Query().Get("key") if key == "" { http.RedirectHandler("/assets/html/index.html", http.StatusMovedPermanently) return } matchInput, err := RetrievePermLink(ctx, key) if err != nil { ctx.Errorf("%v", err) http.Error(rw, err.Error(), http.StatusInternalServerError) return } //TODO: figure out how to get loadRegexp results to evaluate and display to user (need to replace defaults of $scope.regexpInput) //TODO: OR have JS type the presence of ?key= and replace the defaults on page load err = json.NewEncoder(rw).Encode(matchInput) if err != nil { ctx.Errorf("JSON encoding err: %v", err) http.Error(rw, "JSON encoding error", http.StatusInternalServerError) return } }
func main() { logger := log.New(os.Stdout, "[HashDBServer] ", log.LstdFlags) logger.Println("[*] Initializing Hash-Database") hashMix, err := hashdb.OpenMix("db", 10) if err != nil { logger.Println("Error initializing HashMix:", err) return } ghh, err := NewGetHashHandler(hashMix, logger) if err != nil { logger.Println("Error initializing GetHashHandler:", err) return } phh, err := NewPutHashHandler(hashMix, logger) if err != nil { logger.Println("Error initializing PutHashHandler:", err) return } logger.Println("[*] Waiting for clients...") http.Handle("/md5", ghh) http.Handle("/sha1", ghh) http.Handle("/new", phh) // Redirect all other requests to... http.Handle("/", http.RedirectHandler("https://github.com/marpie/hashdb", 301)) http.ListenAndServe(":8080", nil) }
func CreateFrontend(cfg FrontendConfig) (frontend *Frontend, err error) { frontend = &Frontend{cfg: cfg} // Create logger frontend.Log = log.New(frontend.cfg.LogOutput, "frontend: ", log.Ldate|log.Lshortfile) // Create an ElasticSearch connection frontend.elasticSearch, err = CreateElasticSearch(frontend.cfg.ElasticServer) if err != nil { return } // Create a pongo2 template set frontend.templates = pongo2.NewSet("torture") frontend.templates.SetBaseDirectory("templates") // Sub-Apps search, err := CreateSearch(SearchConfig{ Frontend: frontend, }) if err != nil { return } mux := httprouter.New() mux.Handle("GET", "/s", search.Handler) mux.Handler("GET", "/", http.RedirectHandler("/s", 301)) mux.ServeFiles("/static/*filepath", http.Dir("static")) log.Fatal(http.ListenAndServe(frontend.cfg.HttpListen, mux)) return }
func main() { flag.Parse() storage := memory.New(*argSampleSize, *argHistoryDuration) // TODO(monnand): Add stats writer for manager containerManager, err := manager.New(storage) if err != nil { log.Fatalf("Failed to create a Container Manager: %s", err) } if err := lmctfy.Register("/"); err != nil { log.Printf("lmctfy registration failed: %v.", err) log.Print("Running in docker only mode.") if err := docker.Register(containerManager, "/"); err != nil { log.Printf("Docker registration failed: %v.", err) log.Fatalf("Unable to continue without docker or lmctfy.") } } if err := docker.Register(containerManager, "/docker"); err != nil { // Ignore this error because we should work with lmctfy only log.Printf("Docker registration failed: %v.", err) log.Print("Running in lmctfy only mode.") } // Handler for static content. http.HandleFunc(static.StaticResource, func(w http.ResponseWriter, r *http.Request) { err := static.HandleRequest(w, r.URL) if err != nil { fmt.Fprintf(w, "%s", err) } }) // Handler for the API. http.HandleFunc(api.ApiResource, func(w http.ResponseWriter, r *http.Request) { err := api.HandleRequest(containerManager, w, r.URL) if err != nil { fmt.Fprintf(w, "%s", err) } }) // Redirect / to containers page. http.Handle("/", http.RedirectHandler(pages.ContainersPage, http.StatusTemporaryRedirect)) // Register the handler for the containers page. http.HandleFunc(pages.ContainersPage, func(w http.ResponseWriter, r *http.Request) { err := pages.ServerContainersPage(containerManager, w, r.URL) if err != nil { fmt.Fprintf(w, "%s", err) } }) go containerManager.Start() log.Printf("Starting cAdvisor version: %q", info.VERSION) log.Print("About to serve on port ", *argPort) addr := fmt.Sprintf(":%v", *argPort) log.Fatal(http.ListenAndServe(addr, nil)) }
func main() { http.HandleFunc("/", thisLittleWebpage) // set the path URL fmt.Println("server is now running...") // display when server is running go http.ListenAndServe(":8080", http.RedirectHandler("https://localhost:2525/", 301)) // redirect from HTTP to HTTPS http.ListenAndServeTLS(":2525", "cert/cert.pem", "cert/key.pem", nil) // server is now running on HTTPS and load certificates }
// Add will register a pattern with a handler for meth requests. func (p *PatternServeMux) Add(meth string, args ...interface{}) { n := len(args) pat := args[n-2].(string) h := args[n-1] var ph *patHandler switch h.(type) { default: panic("unknown handler type") case nil: ph = &patHandler{pat, nil} case func(http.ResponseWriter, *http.Request): hf := http.HandlerFunc(h.(func(http.ResponseWriter, *http.Request))) ph = &patHandler{pat, hf} case http.Handler: ph = &patHandler{pat, h.(http.Handler)} } p.handlers[meth] = append(p.handlers[meth], ph) if n-3 > -1 { name := args[n-3].(string) p.named[name] = ph } n = len(pat) if n > 0 && pat[n-1] == '/' { p.Add(meth, pat[:n-1], http.RedirectHandler(pat, http.StatusMovedPermanently)) } }
// register an http hander for a particular method and path func (self *Multiplexer) Handle(method, path string, h http.Handler) { self.handlers[method] = append(self.handlers[method], &Handler{path, h}) n := len(path) if n > 0 && path[n-1] == '/' { self.Handle(method, path[:n-1], http.RedirectHandler(path, 301)) } }
func main() { // command line flags // port := flag.Int("port", 80, "port to serve on") dir := flag.String("directory", "web/", "directory of web files") flag.Parse() // handle all requests by serving a file of the same name fs := http.Dir(*dir) fileHandler := http.FileServer(fs) // setup routes router := mux.NewRouter() router.Handle("/", http.RedirectHandler("/static/", 302)) router.Handle("/posts", handler(listPosts)).Methods("GET") router.Handle("/posts", handler(addPost)).Methods("POST") router.Handle("/posts/{id}", handler(getPost)).Methods("GET") router.Handle("/posts/{id}", handler(updatePost)).Methods("POST") router.Handle("/posts/{id}", handler(removePost)).Methods("DELETE") router.PathPrefix("/static/").Handler(http.StripPrefix("/static", fileHandler)) http.Handle("/", router) // bootstrap some data //books = append(books, book{"Ender's Game", "Orson Scott Card", getNextId()}) //books = append(books, book{"Code Complete", "Steve McConnell", getNextId()}) //books = append(books, book{"World War Z", "Max Brooks", getNextId()}) //books = append(books, book{"Pragmatic Programmer", "David Thomas", getNextId()}) //log.Printf("Running on port %d\n", *port) //addr := fmt.Sprintf("127.0.0.1:%d", *port) // this call blocks -- the progam runs here forever //err := http.ListenAndServe(addr, nil) //fmt.Println(err.Error()) }
// setMatch extracts the variables from the URL once a route matches. func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) { // Store host variables. if v.host != nil { hostVars := v.host.regexp.FindStringSubmatch(getHost(req)) if hostVars != nil { for k, v := range v.host.varsN { m.Vars[v] = hostVars[k+1] } } } // Store path variables. if v.path != nil { pathVars := v.path.regexp.FindStringSubmatch(req.URL.Path) if pathVars != nil { for k, v := range v.path.varsN { m.Vars[v] = pathVars[k+1] } // Check if we should redirect. if r.strictSlash { p1 := strings.HasSuffix(req.URL.Path, "/") p2 := strings.HasSuffix(v.path.template, "/") if p1 != p2 { u, _ := url.Parse(req.URL.String()) if p1 { u.Path = u.Path[:len(u.Path)-1] } else { u.Path += "/" } m.Handler = http.RedirectHandler(u.String(), 301) } } } } }
func NewRouter() http.Handler { // Setup session store authKey := securecookie.GenerateRandomKey(64) encryptionKey := securecookie.GenerateRandomKey(32) store := sessions.NewCookieStore( authKey, encryptionKey, ) appContext := &ctx{ sessionStore: store, } router := mux.NewRouter() // Setup the WS Hub here // Add handlers for routes router.Handle("/signup", http.RedirectHandler("/signup.html", 307)).Methods("GET") router.Handle("/signin", appHandler{appContext, signIn}).Methods("POST") // Add handlers for websockets return router }