예제 #1
0
// WebServer starts the web server and serves GET & POST requests
func WebServer(config *Config, publicPath *string) {
	if config.Uchiwa.User != "" && config.Uchiwa.Pass != "" {
		http.Handle("/delete_client", httpauth.SimpleBasicAuth(config.Uchiwa.User, config.Uchiwa.Pass)(http.HandlerFunc(deleteClientHandler)))
		http.Handle("/delete_stash", httpauth.SimpleBasicAuth(config.Uchiwa.User, config.Uchiwa.Pass)(http.HandlerFunc(deleteStashHandler)))
		http.Handle("/get_client", httpauth.SimpleBasicAuth(config.Uchiwa.User, config.Uchiwa.Pass)(http.HandlerFunc(getClientHandler)))
		http.Handle("/get_config", httpauth.SimpleBasicAuth(config.Uchiwa.User, config.Uchiwa.Pass)(http.HandlerFunc(getConfigHandler)))
		http.Handle("/get_sensu", httpauth.SimpleBasicAuth(config.Uchiwa.User, config.Uchiwa.Pass)(http.HandlerFunc(getSensuHandler)))
		http.Handle("/post_event", httpauth.SimpleBasicAuth(config.Uchiwa.User, config.Uchiwa.Pass)(http.HandlerFunc(postEventHandler)))
		http.Handle("/post_stash", httpauth.SimpleBasicAuth(config.Uchiwa.User, config.Uchiwa.Pass)(http.HandlerFunc(postStashHandler)))
		http.Handle("/", httpauth.SimpleBasicAuth(config.Uchiwa.User, config.Uchiwa.Pass)(http.FileServer(http.Dir(*publicPath))))
	} else {
		http.Handle("/delete_client", http.HandlerFunc(deleteClientHandler))
		http.Handle("/delete_stash", http.HandlerFunc(deleteStashHandler))
		http.Handle("/get_client", http.HandlerFunc(getClientHandler))
		http.Handle("/get_config", http.HandlerFunc(getConfigHandler))
		http.Handle("/get_sensu", http.HandlerFunc(getSensuHandler))
		http.Handle("/post_event", http.HandlerFunc(postEventHandler))
		http.Handle("/post_stash", http.HandlerFunc(postStashHandler))
		http.Handle("/", http.FileServer(http.Dir(*publicPath)))
	}

	http.Handle("/health", http.HandlerFunc(healthHandler))
	http.Handle("/health/", http.HandlerFunc(healthHandler))

	listen := fmt.Sprintf("%s:%d", config.Uchiwa.Host, config.Uchiwa.Port)
	logger.Infof("Uchiwa is now listening on %s", listen)
	http.ListenAndServe(listen, nil)
}
예제 #2
0
파일: main.go 프로젝트: changwng/sqliteweb
// initServer initialize and start the web server.
func initServer(db *client.DbClient) {
	// Initialize the API controller
	controllers.Init(db)

	// Staticbin middleware
	goji.Use(gojistaticbin.Staticbin("static", Asset, gojistaticbin.Options{
		SkipLogging: true,
		IndexFile:   "index.html",
	}))

	// Httpauth middleware
	if options.AuthUser != "" && options.AuthPass != "" {
		goji.Use(httpauth.SimpleBasicAuth(options.AuthUser, options.AuthPass))
	}

	goji.Get("/api/info", controllers.Info)
	goji.Get("/api/table", controllers.Tables)
	goji.Get("/api/table/:name", controllers.Table)
	goji.Get("/api/table/:name/info", controllers.TableInfo)
	goji.Get("/api/table/:name/sql", controllers.TableSql)
	goji.Get("/api/table/:name/indexes", controllers.TableIndexes)
	goji.Get("/api/query", controllers.Query)
	goji.Post("/api/query", controllers.Query)

	address := fmt.Sprintf("%s:%d", options.HttpHost, options.HttpPort)
	flag.Set("bind", address)

	go goji.Serve()
}
예제 #3
0
파일: webserver.go 프로젝트: topscore/sup
func StartWebServer(bind, auth string) error {
	err := loadTemplates()
	if err != nil {
		return err
	}

	if auth != "" {
		authParts := strings.Split(auth, ":")
		goji.Use(httpauth.SimpleBasicAuth(authParts[0], authParts[1]))
	}

	goji.Get("/", homeRoute)
	goji.Get("/status", statusRoute)
	goji.Get("/robots.txt", robotsRoute)
	goji.Get("/setEnabled", setEnabledRoute)
	goji.Handle("/config", configRoute)

	listener, err := net.Listen("tcp", bind)
	if err != nil {
		return err
	}

	goji.ServeListener(listener)
	return nil
}
예제 #4
0
파일: factories.go 프로젝트: atmos/conveyor
func newServer(cy *conveyor.Conveyor, c *cli.Context) http.Handler {
	var apiAuth func(http.Handler) http.Handler

	if auth := c.String("auth"); auth != "" {
		parts := strings.Split(auth, ":")
		apiAuth = httpauth.SimpleBasicAuth(parts[0], parts[1])
	} else {
		apiAuth = func(h http.Handler) http.Handler { return h }
	}

	r := mux.NewRouter()
	r.NotFoundHandler = server.NewServer(cy, server.Config{
		APIAuth:      apiAuth,
		GitHubSecret: c.String("github.secret"),
	})

	// Slack webhooks
	if c.String("slack.token") != "" {
		r.Handle("/slack", newSlackServer(cy, c))
	}

	n := negroni.Classic()
	n.UseHandler(r)

	return n
}
예제 #5
0
파일: server.go 프로젝트: jarias/alpha
func main() {
	session, err := mgo.Dial(mongoURI())
	if err != nil {
		log.Fatal(err)
	}
	defer session.Close()

	systemsC := session.DB("").C("systems")

	flag.Parse()
	ctx := context.Background()
	kami.Context = ctx

	kami.Use("/api/", httpauth.SimpleBasicAuth(os.Getenv("BASIC_USERNAME"), os.Getenv("BASIC_PASSWORD")))

	kami.Post("/api/v1/systems", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		system := alpha.System{}

		err := json.NewDecoder(r.Body).Decode(&system)
		if err != nil {
			http.Error(w, err.Error(), 400)
		}

		_, err = systemsC.UpsertId(system.ID, &system)
		if err != nil {
			http.Error(w, err.Error(), 400)
		}

		log.Printf("System %+v recieved", system)

		fmt.Fprint(w, "OK")
	})

	kami.Get("/api/v1/systems.csv", func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		systems := []alpha.System{}

		err := systemsC.Find(nil).All(&systems)
		if err != nil {
			log.Println(err.Error())
			http.Error(w, err.Error(), 400)
		}

		csvWriter := csv.NewWriter(w)
		csvWriter.Write([]string{"ID", "Model", "Serial Number", "Hostname", "OS Name", "OS Version", "Memory Total", "Memory Speed", "Disk Type", "Battery Condition", "Battery Charge Cycles", "Users"})

		for _, s := range systems {
			users := []string{}
			for _, user := range s.Users {
				users = append(users, user.Name)
			}
			csvWriter.Write([]string{s.ID, s.Model, s.SerialNumber, s.Hostname, s.OS.Name, s.OS.Version, s.Memory.Total, s.Memory.Speed, s.Storage.Devices[0].Type, s.Battery.Condition, s.Battery.CycleCount, strings.Join(users, " | ")})
		}

		w.Header().Set("Content-Type", "text/csv")
		w.Header().Set("Content-Disposition", "attachment;filename=systems.csv")
		csvWriter.Flush()
	})

	kami.Serve()
}
예제 #6
0
파일: main.go 프로젝트: a-r-g-v/mitei
func main() {

	punch.Setup()

	goji.Use(httpauth.SimpleBasicAuth("a", "a"))
	goji.Post("/create", CreateController)
	goji.Get("/remove/:id", RemoveController)
	goji.Get("/", IndexController)
	goji.Serve()

}
예제 #7
0
파일: server.go 프로젝트: chrissexton/devd
// Router constructs the main Devd router that serves all requests
func (dd *Devd) Router(logger termlog.TermLog, templates *template.Template) (http.Handler, error) {
	mux := http.NewServeMux()
	hasGlobal := false

	ci := inject.CopyInject{}
	if dd.HasLivereload() {
		ci = livereload.Injector
	}

	for match, route := range dd.Routes {
		if match == "/" {
			hasGlobal = true
		}
		handler := dd.WrapHandler(
			logger,
			route.Endpoint.Handler(templates, ci),
		)
		handler = http.StripPrefix(route.Path, handler)
		mux.Handle(match, handler)
	}
	if dd.HasLivereload() {
		lr := livereload.NewServer("livereload", logger)
		mux.Handle(livereload.EndpointPath, lr)
		mux.Handle(livereload.ScriptPath, http.HandlerFunc(lr.ServeScript))
		if dd.LivereloadRoutes {
			err := WatchRoutes(dd.Routes, lr, dd.Excludes, logger)
			if err != nil {
				return nil, fmt.Errorf("Could not watch routes for livereload: %s", err)
			}
		}
		if len(dd.WatchPaths) > 0 {
			err := WatchPaths(dd.WatchPaths, dd.Excludes, lr, logger)
			if err != nil {
				return nil, fmt.Errorf("Could not watch path for livereload: %s", err)
			}
		}
		dd.lrserver = lr
	}
	if !hasGlobal {
		mux.Handle(
			"/",
			dd.WrapHandler(logger, HandleNotFound(templates)),
		)
	}
	var h = http.Handler(mux)
	if dd.Credentials != nil {
		h = httpauth.SimpleBasicAuth(
			dd.Credentials.username, dd.Credentials.password,
		)(h)
	}
	return hostPortStrip(h), nil
}
예제 #8
0
func main() {
	parseFlags()

	ss := NewHTTPStaticServer(gcfg.Root)
	ss.Theme = gcfg.Theme
	ss.Title = gcfg.Title

	if gcfg.Upload {
		ss.EnableUpload()
	}
	if gcfg.PlistProxy != nil {
		gcfg.PlistProxy.Scheme = "https"
		ss.PlistProxy = gcfg.PlistProxy.String()
	}

	var hdlr http.Handler = ss

	hdlr = accesslog.NewLoggingHandler(hdlr, l)

	// HTTP Basic Authentication
	userpass := strings.SplitN(gcfg.HttpAuth, ":", 2)
	if len(userpass) == 2 {
		user, pass := userpass[0], userpass[1]
		hdlr = httpauth.SimpleBasicAuth(user, pass)(hdlr)
	}
	// CORS
	if gcfg.Cors {
		hdlr = handlers.CORS()(hdlr)
	}
	if gcfg.XHeaders {
		hdlr = handlers.ProxyHeaders(hdlr)
	}

	http.Handle("/", hdlr)
	http.HandleFunc("/-/sysinfo", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		data, _ := json.Marshal(map[string]interface{}{
			"version": VERSION,
		})
		w.Write(data)
	})

	log.Printf("Listening on addr: %s\n", strconv.Quote(gcfg.Addr))

	var err error
	if gcfg.Key != "" && gcfg.Cert != "" {
		err = http.ListenAndServeTLS(gcfg.Addr, gcfg.Cert, gcfg.Key, nil)
	} else {
		err = http.ListenAndServe(gcfg.Addr, nil)
	}
	log.Fatal(err)
}
예제 #9
0
func startFrontend(cfg *proxy.Config, s *proxy.ProxyServer) {
	r := mux.NewRouter()
	r.HandleFunc("/stats", s.StatsIndex)
	r.PathPrefix("/").Handler(http.FileServer(http.Dir("./www/")))
	var err error
	if len(cfg.Frontend.Password) > 0 {
		auth := httpauth.SimpleBasicAuth(cfg.Frontend.Login, cfg.Frontend.Password)
		err = http.ListenAndServe(cfg.Frontend.Listen, auth(r))
	} else {
		err = http.ListenAndServe(cfg.Frontend.Listen, r)
	}
	if err != nil {
		log.Fatal(err)
	}
}
예제 #10
0
파일: gosuv.go 프로젝트: codeskyblue/gosuv
func actionStartServer(c *cli.Context) error {
	suv, hdlr, err := newSupervisorHandler()
	if err != nil {
		log.Fatal(err)
	}
	auth := cfg.Server.HttpAuth
	if auth.Enabled {
		hdlr = httpauth.SimpleBasicAuth(auth.User, auth.Password)(hdlr)
	}
	http.Handle("/", hdlr)

	addr := cfg.Server.Addr
	if c.Bool("foreground") {
		suv.AutoStartPrograms()
		log.Printf("server listen on %v", addr)
		log.Fatal(http.ListenAndServe(addr, nil))
	} else {
		if checkServerStatus() == nil {
			fmt.Println("server is already running")
			return nil
		}
		logPath := filepath.Join(defaultConfigDir, "gosuv.log")
		logFd, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
		if err != nil {
			log.Fatalf("create file %s failed: %v", logPath, err)
		}
		cmd := exec.Command(os.Args[0], "start-server", "-f")
		cmd.Stdout = logFd
		cmd.Stderr = logFd
		err = cmd.Start()
		if err != nil {
			log.Fatal(err)
		}
		select {
		case err = <-GoFunc(cmd.Wait):
			log.Fatalf("server started failed, %v", err)
		case <-time.After(200 * time.Millisecond):
			showAddr := addr
			if strings.HasPrefix(addr, ":") {
				showAddr = "0.0.0.0" + addr
			}
			fmt.Printf("server started, listening on %s\n", showAddr)
		}
	}
	return nil
}
예제 #11
0
파일: main.go 프로젝트: a-r-g-v/almost-ddns
func main() {

	// move binary directory
	dir := path.Dir(os.Args[0])
	os.Chdir(dir)

	// load config
	if _, err := toml.DecodeFile("config.toml", &config); err != nil {
		panic(err)
	}

	flag.Set("bind", config.Web.Bind)
	go work()
	goji.Use(httpauth.SimpleBasicAuth(config.Web.User, config.Web.Pass))
	goji.Get("/v1/stat", StatAPIContoller)
	goji.Serve()

}
예제 #12
0
func main() {
	auth := httpauth.SimpleBasicAuth("dave", "secret")

	router := mux.NewRouter()
	config := Config{}
	config.Name = "my admin test page"

	log.Println("Metrics")
	minion.SetupMetrics(metrics.DefaultRegistry, config.Metrics)

	log.Println("Admin routes")
	admin := mux.NewRouter()
	rest.AddConfigRoute(admin, config)
	rest.AddMetricsRoute(admin, metrics.DefaultRegistry)
	rest.Mount(router, "/admin", auth(admin))

	log.Println("Listening")
	rest.ListenAndServe(8080, router)
}
예제 #13
0
func NewRouter() *mux.Router {
	// read from .htpasswd file

	router := mux.NewRouter().StrictSlash(true)

	for _, route := range routes {
		var handler http.Handler

		handler = route.HandlerFunc
		handler = Logger(handler, route.Name)
		router.
			Methods(route.Method).
			Path(route.Pattern).
			Name(route.Name).
			Handler(httpauth.SimpleBasicAuth(config.DBUser, config.DBPassword)(handler))
	}

	router.PathPrefix("/").Handler(Logger(http.FileServer(http.Dir("./public/")), "/"))

	return router
}
예제 #14
0
파일: main.go 프로젝트: mikeflynn/iwillvote
func main() {
	flag.Parse()

	// Load Templates
	Templates = template.Must(template.ParseGlob(*WebRoot + "/templates/*"))

	log.Printf("Web root directory set to: %s", *WebRoot)

	// Start message services...
	go sendService()
	go receiveService()

	// Start web server...
	r := mux.NewRouter()

	// Static files
	r.PathPrefix("/static/").Handler(http.FileServer(http.Dir(*WebRoot)))

	// API Endpoints
	r.HandleFunc("/api/user/add/", addUserHandler).Methods("POST")
	//r.HandleFunc("/api/user/remove/", removeUserHandler).Methods("POST")

	// Admin Endpoints
	ar := mux.NewRouter().PathPrefix("/admin").Subrouter()
	ar.HandleFunc("/", AdminIndexHandler)
	ar.HandleFunc("/messages", AdminMessagesHandler).Methods("POST", "GET")
	ar.HandleFunc("/users", AdminUsersHandler)
	ar.HandleFunc("/users/{user:[\\w]+@[\\w]+}", AdminUserDetailHandler)
	r.PathPrefix("/admin").Handler(httpauth.SimpleBasicAuth(os.Getenv("ADMIN_USER"), os.Getenv("ADMIN_PASS"))(ar))

	// Pages
	r.HandleFunc("/unsubscribe", unsubHandler).Methods("POST", "GET")
	r.HandleFunc("/code/{code:[0-9a-f]{5,40}}", codeHandler)
	r.HandleFunc("/{page:[a-z]*}", pageHandler)
	log.Println("Web server running on " + *Port)

	http.ListenAndServe(":"+*Port, r)
}
예제 #15
0
func NewRouter() *mux.Router {

	router := mux.NewRouter().StrictSlash(false)
	for _, route := range routes {
		var handler http.Handler

		if route.Secure {
			handler = httpauth.SimpleBasicAuth("admin", *adminPW)(route.HandlerFunc)
		} else {
			handler = route.HandlerFunc
		}

		handler = HTTPProvider(handler, route.Name)

		router.
			Methods(route.Method).
			Path(route.Pattern).
			Name(route.Name).
			Handler(handler)

	}

	return router
}
예제 #16
0
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fn := httpauth.SimpleBasicAuth(h.User, h.Pass)
	fn(h.next).ServeHTTP(w, r)
}
예제 #17
0
func main() {
	rand.Seed(time.Now().Unix())
	flag.Parse()

	// This is only used when we're running in -dev mode with bindata
	rootDir, _ = osext.ExecutableFolder()
	rootDir = path.Join(rootDir, "web")

	// Parse configuration
	cfg, err := config.LoadFromFile(*configFile)
	if err != nil {
		log.Fatalln("Error loading config", err)
	}

	// Templates
	amberTmpl, err := Asset("templates/index.amber")
	if err != nil {
		log.Fatalln("Could not load index template:", err)
	}
	tmpl := amber.MustCompile(string(amberTmpl), amber.Options{})

	// Setup the web UI
	router := httprouter.New()
	router.Handler("GET", *metricsPath, prometheus.Handler()) // Prometheus
	// Static asset handling
	router.GET("/static/*filepath", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		reqpath := ps.ByName("filepath")
		realpath := path.Join("static", reqpath)
		b, err := Asset(realpath)
		if err != nil {
			log.Debugln("Could not find asset: ", err)
			return
		} else {
			w.Write(b)
		}

	})

	var monitoredHosts []*pollers.Host

	router.GET("/", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
		data := struct {
			Cfg   *config.Config
			Hosts *[]*pollers.Host
		}{
			Cfg:   cfg,
			Hosts: &monitoredHosts,
		}
		err := tmpl.Execute(w, &data)
		if err != nil {
			log.Errorln("Error rendering template", err)
		}
	})

	// Initialize the host pollers
	monitoredHosts = make([]*pollers.Host, len(cfg.Hosts))

	// We don't allow duplicate hosts, but also don't want to panic just due
	// to a typo, so keep track and skip duplicates here.
	seenHosts := make(map[string]bool)

	realidx := 0
	for _, hostCfg := range cfg.Hosts {
		log.Debugln("Setting up poller for: ", hostCfg.Hostname)
		if *skipPing {
			hostCfg.PingDisable = true
		}
		if _, ok := seenHosts[hostCfg.Hostname]; ok {
			log.Warnln("Discarding repeat configuration of same hostname", hostCfg.Hostname)
			continue
		}
		host := pollers.NewHost(hostCfg)
		monitoredHosts[realidx] = host
		prometheus.MustRegister(host)

		seenHosts[hostCfg.Hostname] = true
		realidx++
	}

	// Trim monitoredHosts to the number we actually used
	monitoredHosts = monitoredHosts[0:realidx]

	// This is the dispatcher. It is responsible for invoking the doPoll method
	// of hosts.
	connectionLimiter := pollers.NewLimiter(*maxConnections)
	hostQueue := make(chan *pollers.Host)

	// Start the host dispatcher
	go func() {
		for host := range hostQueue {
			go host.Poll(connectionLimiter, hostQueue)
		}
	}()

	// Do the initial host dispatch
	go func() {
		for _, host := range monitoredHosts {
			log.Debugln("Starting polling for hosts")
			hostQueue <- host
		}
	}()

	var handler http.Handler

	// If basic auth is requested, enable it for the interface.
	if cfg.BasicAuthUsername != "" && cfg.BasicAuthPassword != "" {
		basicauth := httpauth.SimpleBasicAuth(cfg.BasicAuthUsername,
			cfg.BasicAuthPassword)
		handler = basicauth(router)
	} else {
		handler = router
	}

	// If TLS certificates are specificed, use TLS
	if cfg.TLSCertificatePath != "" && cfg.TLSKeyPath != "" {
		log.Infof("Listening on (TLS-enabled) %s", *listenAddress)
		err = http.ListenAndServeTLS(*listenAddress,
			cfg.TLSCertificatePath, cfg.TLSKeyPath, handler)
	} else {
		log.Infof("Listening on %s", *listenAddress)
		err = http.ListenAndServe(*listenAddress, handler)
	}

	if err != nil {
		log.Fatal(err)
	}
}