// main sets up the routes (thanks Gorilla!). func main() { r := mux.NewRouter() r.HandleFunc("/", showIndex) r.HandleFunc("/about", showAbout) r.HandleFunc("/archives", showArchives) r.PathPrefix("/static"). Handler(http.StripPrefix("/static", http.FileServer(http.Dir(staticPath)))) // Password protect data refreshing authenticator := auth.NewBasicAuthenticator( "Refresh data", auth.HtpasswdFileProvider(*htpasswd)) r.HandleFunc("/refresh", auth.JustCheck(authenticator, showRefresh)) // These must be last. The first shows blog posts, the second adds comments. r.HandleFunc("/{postname}", showPost).Methods("GET") r.HandleFunc("/{postname}", addComment).Methods("POST") // Captcha! http.Handle("/captcha/", captcha.Server(captcha.StdWidth, captcha.StdHeight)) // Okay, let Gorilla do its work. http.Handle("/", r) http.ListenAndServe(":8082", nil) }
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 }
// Creates out basicAuth Filter // The first params specifies the used htpasswd file // The second is optional and defines the realm name func (spec *basicSpec) CreateFilter(config []interface{}) (filters.Filter, error) { if len(config) == 0 { return nil, filters.ErrInvalidFilterParameters } configFile, ok := config[0].(string) if !ok { return nil, filters.ErrInvalidFilterParameters } realmName := DefaultRealmName if len(config) == 2 { if definedName, ok := config[1].(string); ok { realmName = definedName } } htpasswd := auth.HtpasswdFileProvider(configFile) authenticator := auth.NewBasicAuthenticator(realmName, htpasswd) return &basic{ authenticator: authenticator, realmDefinition: ForceBasicAuthHeaderValue + `"` + realmName + `"`, }, nil }
func runServer() { secrets := auth.HtpasswdFileProvider(".htpasswd") a := auth.BasicAuthenticator("oldbailey", secrets) http.HandleFunc("/static/", view.StaticHandler) http.HandleFunc("/case/", a(view.CaseHandler)) http.HandleFunc("/search", a(view.SearchHandler)) http.HandleFunc("/cache", a(view.CacheHandler)) log.Println("Staring server on port 2258") log.Fatal(http.ListenAndServe(":2258", nil)) }
func StartHTTPServer(port string) { htpasswd := auth.HtpasswdFileProvider(conf.PasswdFile) authenticator := auth.NewBasicAuthenticator("Basic realm", htpasswd) http.HandleFunc(ROUTE_INSERT, authenticator.Wrap(insertHandler)) http.HandleFunc(ROUTE_DELETE, authenticator.Wrap(deleteHandler)) http.HandleFunc(ROUTE_STATIC, authenticator.Wrap(staticHandler)) http.HandleFunc(ROUTE_GET, authenticator.Wrap(getHandler)) http.HandleFunc(ROUTE_LIST, authenticator.Wrap(listHandler)) //http.ListenAndServe(port, nil) http.ListenAndServeTLS(port, conf.TLSPemFile, conf.TLSKeyFile, nil) }
func main() { flag.Parse() PersistenceObj = GetPersistenceLayer(*persistence) if PersistenceObj == nil { log.Err("Unable to load persistence plugin " + *persistence) panic("Dying") } var err error ConfigObj, err = PersistenceObj.GetConfig() if err != nil { log.Err("Unable to load config from persistence plugin " + *persistence) panic("Dying") } if ConfigObj.PidFile != *haproxyPidFile { ConfigObj.PidFile = *haproxyPidFile } r := mux.NewRouter() // Define paths sub := r.PathPrefix("/api").Subrouter() // Wire the UI (outside of muxer) http.Handle("/ui/", http.StripPrefix("/ui/", http.FileServer(http.Dir(*uiLocation)))) // Display handlers sub.HandleFunc("/config", configHandler).Methods("GET") sub.HandleFunc("/reload", configReloadHandler).Methods("GET") sub.HandleFunc("/backend/{backend}", backendHandler).Methods("GET") sub.HandleFunc("/backend/{backend}", backendAddHandler).Methods("POST") sub.HandleFunc("/backend/{backend}", backendDeleteHandler).Methods("DELETE") sub.HandleFunc("/backend/{backend}/server/{server}", backendServerHandler).Methods("GET") sub.HandleFunc("/backend/{backend}/server/{server}", backendServerAddHandler).Methods("POST") sub.HandleFunc("/backend/{backend}/server/{server}", backendServerDeleteHandler).Methods("DELETE") s := &http.Server{ Addr: *bind, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } h := auth.HtpasswdFileProvider(*htpasswd) a := auth.NewBasicAuthenticator("haproxy config", h) http.Handle("/", a.Wrap(func(w http.ResponseWriter, ar *auth.AuthenticatedRequest) { r.ServeHTTP(w, &ar.Request) })) log.Err(s.ListenAndServe().Error()) }
func (h *httpServer) Listen(address string) error { fs := http.FileServer(http.Dir("web/assets")) secrets := auth.HtpasswdFileProvider(h.secrets) authenticator := auth.NewBasicAuthenticator("Basic Realm", secrets) http.HandleFunc("/", h.Root) http.Handle("/assets/", http.StripPrefix("/assets/", fs)) http.HandleFunc("/songs", h.Songs) http.HandleFunc("/song/", h.Song) http.HandleFunc("/ws", ws.Handle) http.HandleFunc("/play/", authenticator.Wrap(h.Play)) return http.ListenAndServe(address, nil) }
func main() { pwd, _ := os.Getwd() //Set config path and type viper.SetConfigName("config") viper.AddConfigPath(pwd) viper.AddConfigPath("/etc/ddesktop/") viper.SetConfigType("yaml") //Read config err := viper.ReadInConfig() if err != nil { log.Fatalln(err) } log.Println(viper.GetString("container.prefix")) //Cleanup existing containers dockerhandler.CleanUp() //Pull new docker image if viper.GetBool("container.pull") { dockerhandler.PullImage() } //Get authentication setting htpasswd := auth.HtpasswdFileProvider(viper.GetString("htpasswd.path")) authenticator := auth.NewBasicAuthenticator(".ddesktop", htpasswd) //Start server log.Printf("Starting server on http://0.0.0.0:" + viper.GetString("server.port.http") + " and https://0.0.0.0:" + viper.GetString("server.port.https") + "...") http.Handle("/websockify", auth.JustCheck(authenticator, wsproxy.WsProxy())) http.HandleFunc("/", auth.JustCheck(authenticator, server.Static())) go func() { if err := http.ListenAndServeTLS(":"+viper.GetString("server.port.https"), viper.GetString("ssl.cert"), viper.GetString("ssl.key"), nil); err != nil { log.Fatalln(err) } }() if err := http.ListenAndServe(":"+viper.GetString("server.port.http"), http.HandlerFunc(server.RedirectHttps)); err != nil { log.Fatalln(err) } }
func main() { folderPath, errpath := osext.ExecutableFolder() if errpath != nil { fmt.Printf("Couldn't get cwd. Check permissions!\n") return } if _, err := os.Stat(folderPath + ".htpasswd"); os.IsNotExist(err) { fmt.Printf(folderPath + ".htpasswd doesn't exist in cwd!\n") return } secrets := auth.HtpasswdFileProvider(folderPath + ".htpasswd") authenticator := auth.NewBasicAuthenticator("Seyes Echelon", secrets) http.HandleFunc("/record_log", auth.JustCheck(authenticator, handle)) fmt.Println("Server starting on port " + os.Args[1] + " ....\n") http.ListenAndServe(":"+os.Args[1], nil) }
func New(runInDebugMode bool, templatesLocation string, usersPasswordFileLocation string, storageFactory model.VFStorageGroup, srvlog *logs.ServerLog) http.Handler { if defaultRouter != nil { return defaultRouter } serverlog = srvlog defaultUserAuthenticator = auth.NewBasicAuthenticator("myrealm", auth.HtpasswdFileProvider(usersPasswordFileLocation)) defaultStorageFactory = storageFactory results.TemplatesDir = templatesLocation results.DebugMode = runInDebugMode defaultRouter = mux.NewRouter() adminRouter := mux.NewRouter() apiRouter := mux.NewRouter() handleVFolder(apiRouter) handleCtrlPanel(adminRouter) handlePlayground(apiRouter) defaultRouter.PathPrefix("/api").Handler( negroni.New( negroni.HandlerFunc(authorized), negroni.Wrap(apiRouter), ), ) defaultRouter.PathPrefix("/admin").Handler( negroni.New( negroni.HandlerFunc(authorized), negroni.HandlerFunc(adminOnly), negroni.Wrap(adminRouter), ), ) defaultRouter.PathPrefix("/static").Handler(http.StripPrefix("/static", http.FileServer(http.Dir("./server/static")))) return defaultRouter }
func main() { parseConfig() bootstrap() // try open the repo repo, err := git.OpenRepository(".") if err != nil { log.Printf("git repository not found at current directory. please use `-init` switch or run `git init` in this directory") log.Fatal(err) os.Exit(2) } else { repo.Free() } // load auth file if _, err := os.Stat(wikiConfig.auth); len(wikiConfig.auth) > 0 && (!os.IsNotExist(err)) { authenticator = auth.NewBasicAuthenticator("strapdown.ztx.io", auth.HtpasswdFileProvider(wikiConfig.auth)) // should we replace the url here? log.Printf("use authentication file: %s", wikiConfig.auth) } else { log.Printf("authentication file not exist, disable http authentication") } if _, err := os.Stat(".md"); os.IsNotExist(err) { // release a default .md log.Print("Release default .md") file, err := Asset("_static/.md") if err != nil { log.Printf("[ WARN ] fail to load .md") } err = ioutil.WriteFile(".md", file, 0644) if err != nil { log.Printf("[ WARN ] cannot write default .md: %v", err) } } if _, err := os.Stat("favicon.ico"); os.IsNotExist(err) { // release the files log.Print("Release the favicon.ico") file, err := Asset("_static/fav.ico") if err != nil { log.Printf("[ WARN ] fail to load favicon.ico") } err = ioutil.WriteFile("favicon.ico", file, 0644) if err != nil { log.Printf("[ WARN ] cannot write default favicon.ico: %v", err) } } http.HandleFunc("/", handleFunc) // listen on the (multi) addresss cnt := 0 ch := make(chan bool) for _, host := range strings.Split(wikiConfig.addr, ",") { cnt += 1 log.Printf("[ %d ] listening on %s", cnt, host) go func(h string, aid int) { e := http.ListenAndServe(h, nil) if e != nil { log.Printf("[ %d ] failed to bind on %s: %v", aid, h, e) ch <- false } else { ch <- true } }(host, cnt) } for cnt > 0 { <-ch cnt -= 1 } }
func main() { programName := os.Args[0] absPath, _ := filepath.Abs(programName) haproxyConsoleRoot = path.Dir(path.Dir(absPath)) port := flag.String("p", "9090", "port to run the web server") configuration := flag.String("config", "", "path to the app config file") toolMode := flag.Bool("t", false, "run this program as a tool to export data from database to json or from json to database") flag.Parse() configPath := *configuration if configPath == "" { defaultConfigPath := haproxyConsoleRoot + "/conf/app_conf.ini" fmt.Printf("You not set the configPath, so try to use the default config path: %s\n", defaultConfigPath) if _, e := os.Stat(defaultConfigPath); os.IsNotExist(e) { fmt.Println("Not Exit default config file") os.Exit(1) } else { configPath = defaultConfigPath } } var err error logger = getLogger() appConf, err = config.ParseConfig(configPath) if err != nil { fmt.Println(err) return } if *toolMode { // 数据转换存储方式 err := tools.StorageTransform(appConf) tools.CheckError(err) } else { // 存储连接初始化 db, err = applicationDB.InitStoreConnection(appConf) if err != nil { logger.Fatalln(err) os.Exit(1) } defer db.Close() // 请求路由 http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(haproxyConsoleRoot+"/static/")))) // basic auth user: admin, passwd: 1qazXSW@ authenticator := auth.NewBasicAuthenticator("HAProxyConsole", auth.HtpasswdFileProvider(haproxyConsoleRoot+"/conf/md5passwd")) http.HandleFunc("/applyvport", authenticator.Wrap(applyVPort)) http.HandleFunc("/edittask", authenticator.Wrap(editTask)) http.HandleFunc("/listenlist", authenticator.Wrap(getListenList)) http.HandleFunc("/dellistentask", authenticator.Wrap(delListenTask)) http.HandleFunc("/applyconf", authenticator.Wrap(applyConf)) http.HandleFunc("/statspage", statsPage) http.HandleFunc("/", authenticator.Wrap(getHomePage)) // 启动http服务 err = http.ListenAndServe(":"+*port, nil) if err != nil { logger.Fatalln("ListenAndServe: ", err) } } }
func NewHttpBasicAuthenticator(htpasswdFile string) *HttpBasicAuthenticator { return &HttpBasicAuthenticator{ //secretFunc: httpauth.HtpasswdFileProvider(htpasswdFile), basicAuth: httpauth.NewBasicAuthenticator("vindalu", httpauth.HtpasswdFileProvider(htpasswdFile)), } }
func main() { parseConfig() bootstrap() if wikiConfig.version { fmt.Printf("Strapdown Wiki Server - v%s\n", SERVER_VERSION) os.Exit(0) } // try open the repo repo, err := git.OpenRepository(".") if err != nil { log.Printf("git repository not found at current directory. please use `-init` switch or run `git init` in this directory") log.Fatal(err) os.Exit(2) } else { repo.Free() } // load auth file if _, err := os.Stat(wikiConfig.auth); len(wikiConfig.auth) > 0 && (!os.IsNotExist(err)) { authenticator = auth.NewBasicAuthenticator("strapdown.ztx.io", auth.HtpasswdFileProvider(wikiConfig.auth)) // should we replace the url here? log.Printf("use authentication file: %s", wikiConfig.auth) } else { log.Printf("authentication file not exist, disable http authentication") } if _, err := os.Stat("_static"); os.IsNotExist(err) { // release the files log.Print("Seems you don't have `_static` folder, release one to hold the static file") files := AssetNames() for _, name := range files { if strings.HasSuffix(name, ".html") || strings.HasSuffix(name, "fav.ico") { continue } file, err := Asset(name) if err != nil { log.Printf("[ WARN ] fail to load: %s", name) } err = os.MkdirAll(path.Dir(name), 0700) if err != nil { log.Printf("[ WARN ] fail to create folder: %s", path.Dir(name)) } err = ioutil.WriteFile(name, file, 0644) if err != nil { log.Printf("[ WARN ] cannot write file: %v", err) } } } if _, err := os.Stat(".md"); os.IsNotExist(err) { // release a default .md log.Print("Release default .md") file, err := Asset("_static/.md") if err != nil { log.Printf("[ WARN ] fail to load .md") } err = ioutil.WriteFile(".md", file, 0644) if err != nil { log.Printf("[ WARN ] cannot write default .md: %v", err) } } if _, err := os.Stat("favicon.ico"); os.IsNotExist(err) { // release the files log.Print("Release the favicon.ico") file, err := Asset("_static/fav.ico") if err != nil { log.Printf("[ WARN ] fail to load favicon.ico") } err = ioutil.WriteFile("favicon.ico", file, 0644) if err != nil { log.Printf("[ WARN ] cannot write default favicon.ico: %v", err) } } http.HandleFunc("/", handleFunc) // listen on the (multi) addresss cnt := 0 ch := make(chan bool) for _, host := range strings.Split(wikiConfig.addr, ",") { cnt += 1 log.Printf("[ %d ] listening on %s", cnt, host) go func(h string, aid int) { e := http.ListenAndServe(h, nil) if e != nil { log.Printf("[ %d ] failed to bind on %s: %v", aid, h, e) ch <- false } else { ch <- true } }(host, cnt) } for cnt > 0 { <-ch cnt -= 1 } }
func main() { var config_path = flag.String("config", "", "Path to the config file") flag.Parse() if *config_path == "" { log.Fatal("Give path to the config file with -path=") } b, err := ioutil.ReadFile(*config_path) if err != nil { log.Fatal(err) } err = json.Unmarshal(b, &config) if err != nil { log.Fatal(err) } if config.Port == 0 || config.Auth_file == "" || len(config.Log_files) == 0 { log.Fatal("Invalid configuration") } watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } go func() { for { select { case ev := <-watcher.Event: log.Println("event:", ev) case err := <-watcher.Error: log.Println("error:", err) } } }() for _, v := range config.Log_files { log.Print(v.Path) err = watcher.Watch(v.Path) if err != nil { log.Fatal(err) } } secrets := auth.HtpasswdFileProvider(config.Auth_file) authenticator := auth.BasicAuthenticator("logserv", secrets) http.HandleFunc("/", authenticator(rootHandler)) http.Handle("/websocket", websocket.Handler(EchoServer)) listen_address := fmt.Sprintf(":%d", config.Port) http.ListenAndServe(listen_address, nil) if err != nil { panic("ListenAndServe: " + err.Error()) } watcher.Close() }
func main() { defer glog.Flush() flag.Parse() if *versionFlag { fmt.Printf("cAdvisor version %s\n", info.VERSION) os.Exit(0) } setMaxProcs() storageDriver, err := NewStorageDriver(*argDbDriver) if err != nil { glog.Fatalf("Failed to connect to database: %s", err) } sysFs, err := sysfs.NewRealSysFs() if err != nil { glog.Fatalf("Failed to create a system interface: %s", err) } containerManager, err := manager.New(storageDriver, sysFs) 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) } // Basic health handler. if err := healthz.RegisterHandler(); err != nil { glog.Fatalf("Failed to register healthz handler: %s", err) } // Validation/Debug handler. http.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(containerManager); err != nil { glog.Fatalf("Failed to register API handlers: %s", err) } // Redirect / to containers page. http.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) http.HandleFunc(static.StaticResource, authenticator.Wrap(staticHandler)) if err := pages.RegisterHandlersBasic(containerManager, authenticator); err != nil { glog.Fatalf("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) http.HandleFunc(static.StaticResource, authenticator.Wrap(staticHandler)) if err := pages.RegisterHandlersDigest(containerManager, authenticator); err != nil { glog.Fatalf("Failed to register pages digest handlers: %s", err) } authenticated = true } // Change handler based on authenticator initalization if !authenticated { http.HandleFunc(static.StaticResource, staticHandlerNoAuth) if err := pages.RegisterHandlersBasic(containerManager, nil); err != nil { glog.Fatalf("Failed to register pages handlers: %s", err) } } // Start the manager. if err := containerManager.Start(); err != nil { glog.Fatalf("Failed to start container manager: %v", err) } // Install signal handler. installSignalHandler(containerManager) glog.Infof("Starting cAdvisor version: %q on port %d", info.VERSION, *argPort) addr := fmt.Sprintf("%s:%d", *argIp, *argPort) glog.Fatal(http.ListenAndServe(addr, nil)) }