예제 #1
0
func NewGlobals() *Globals {
	globals := &Globals{}
	globals.confFilename = *configFilename
	globals.ReloadConfig()
	globals.StatsServer = stats.New()
	globals.StatsAdmin = stats.New()
	return globals
}
func getNegroniHandlers(ctx *RouterContext.RouterContext, router *mux.Router) []negroni.Handler {
	tmpArray := []negroni.Handler{}

	// fullRecoveryStackMessage := GlobalConfigSettings.Common.DevMode

	routerRecoveryWrapper := &tmpRouterRecoveryWrapper{ctx.Logger}

	// tmpArray = append(tmpArray, gzip.Gzip(gzip.DefaultCompression))
	tmpArray = append(tmpArray, NewRecovery(routerRecoveryWrapper.onRouterRecoveryError)) //recovery.JSONRecovery(fullRecoveryStackMessage))
	tmpArray = append(tmpArray, negroni.NewLogger())

	if ctx.Settings.IsDevMode() {
		middleware := stats.New()
		router.HandleFunc("/stats.json", func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/json")

			stats := middleware.Data()

			b, _ := json.Marshal(stats)

			w.Write(b)
		})
		tmpArray = append(tmpArray, middleware)
	}

	return tmpArray
}
예제 #3
0
func main() {
	env := Env{
		Metrics: stats.New(),
		Render:  render.New(),
	}
	router := mux.NewRouter()

	router.HandleFunc("/", makeHandler(env, HomeHandler))
	router.HandleFunc("/healthcheck", makeHandler(env, HealthcheckHandler)).Methods("GET")
	router.HandleFunc("/metrics", makeHandler(env, MetricsHandler)).Methods("GET")

	router.HandleFunc("/users", makeHandler(env, ListUsersHandler)).Methods("GET")
	router.HandleFunc("/users/{uid:[0-9]+}", makeHandler(env, GetUserHandler)).Methods("GET")
	router.HandleFunc("/users", makeHandler(env, CreateUserHandler)).Methods("POST")
	router.HandleFunc("/users/{uid:[0-9]+}", makeHandler(env, UpdateUserHandler)).Methods("PUT")
	router.HandleFunc("/users/{uid:[0-9]+}", makeHandler(env, DeleteUserHandler)).Methods("DELETE")

	router.HandleFunc("/users/{uid}/passports", makeHandler(env, PassportsHandler)).Methods("GET")
	router.HandleFunc("/passports/{pid:[0-9]+}", makeHandler(env, PassportsHandler)).Methods("GET")
	router.HandleFunc("/users/{uid}/passports", makeHandler(env, PassportsHandler)).Methods("POST")
	router.HandleFunc("/passports/{pid:[0-9]+}", makeHandler(env, PassportsHandler)).Methods("PUT")
	router.HandleFunc("/passports/{pid:[0-9]+}", makeHandler(env, PassportsHandler)).Methods("DELETE")

	n := negroni.Classic()
	n.Use(env.Metrics)
	n.UseHandler(router)
	fmt.Println("Starting server on :3009")
	n.Run(":3009")
}
예제 #4
0
// NewWebService provides a way to create a new blank WebService
func NewWebService() WebService {
	ws := WebService{}

	// add standard routes
	// Stats controller
	ws.stats = stats.New()
	statsController := NewWebController("/stats")
	statsController.AddMethodHandler(Get, func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.WriteHeader(http.StatusOK)
		b, _ := json.Marshal(ws.stats.Data())
		w.Write(b)
	})
	ws.AddWebController(statsController)

	// Heartbeat controller (echoes the default version info)
	heartbeatController := NewWebController("/heartbeat")
	heartbeatController.AddMethodHandler(Get, func(w http.ResponseWriter, r *http.Request) {
		v := Version{}
		v.Hydrate()
		render.JSON(w, http.StatusOK, v)
	})
	ws.AddWebController(heartbeatController)

	return ws
}
예제 #5
0
파일: api.go 프로젝트: kerkerj/gtg15-demo
func (api *ApiEcho) Handler() http.Handler {
	// Echo instance
	e := echo.New()

	// Middleware
	e.Use(mw.Logger())
	e.Use(mw.Recover())

	// Serve static files
	e.Static("/", "./public")

	// stats https://github.com/thoas/stats
	s := stats.New()
	e.Use(s.Handler)
	e.Get("/stats", func(c *echo.Context) error {
		return c.JSON(http.StatusOK, s.Data())
	})

	// ping
	e.Get("/ping", pingHandler())
	// Set RGB
	e.Get("/rgb/:rgb", rgbHandler(api))
	// SetStabilization
	e.Get("/stable/:bool", stableHandler(api))
	// SetBackLED
	e.Get("/backled/:level", backLedHandler(api))
	// SetHeading
	e.Get("/heading/:heading", headingHandler(api))
	// Roll
	e.Get("/roll/:speed/head/:heading", rollHandler(api))
	// SetRotationRate
	e.Get("/rotate_rate/:level", rotationRateHandler(api))

	return e
}
예제 #6
0
파일: server.go 프로젝트: ch3lo/inspector
func main() {
	middleware := stats.New()

	m := martini.Classic()
	m.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte("{\"hello\": \"world\"}"))
	})
	m.Get("/stats", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")

		stats := middleware.Data()

		b, _ := json.Marshal(stats)

		w.Write(b)
	})

	m.Use(func(c martini.Context, w http.ResponseWriter, r *http.Request) {
		beginning, recorder := middleware.Begin(w)

		c.Next()

		middleware.End(beginning, recorder)
	})
	m.Run()
}
예제 #7
0
파일: server.go 프로젝트: ch3lo/inspector
func main() {
	middleware := stats.New()

	mux := http.NewServeMux()

	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte("{\"hello\": \"world\"}"))
	})

	mux.HandleFunc("/stats", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")

		stats := middleware.Data()

		b, _ := json.Marshal(stats)

		w.Write(b)
	})

	n := negroni.Classic()
	n.Use(middleware)
	n.UseHandler(mux)
	n.Run(":3000")
}
예제 #8
0
파일: main.go 프로젝트: plumbum/go-samples
func main() {

	demoData := Data{
		Id:   5,
		Name: "User name",
		Tags: []string{"people", "customer", "developer"},
	}

	e := echo.New()
	e.SetDebug(true)
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())

	s := stats.New()
	e.Use(standard.WrapMiddleware(s.Handler))

	e.GET("/xml", func(c echo.Context) error {
		return c.XML(200, demoData)
	})

	e.GET("/json", func(c echo.Context) error {
		return c.JSON(200, demoData)
	})

	e.GET("/error", func(c echo.Context) error {
		return echo.NewHTTPError(500, "Error here")
	})

	e.Run(standard.New(":8888"))

}
예제 #9
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	fetchFeed()

	e := echo.New()
	e.Use(mw.Logger())
	e.Use(mw.Recover())
	e.Use(mw.StripTrailingSlash())
	e.Use(mw.Gzip())
	e.Use(cors.Default().Handler)

	bundle, _ := ioutil.ReadFile("./build/bundle.js")

	// stats
	s := stats.New()
	e.Use(s.Handler)
	e.Get("/stats", func(c *echo.Context) error {
		return c.JSON(http.StatusOK, s.Data())
	})
	// static files
	e.Static("/public/css", "public/css")
	e.Static("/universal.js", "./build/bundle.js")
	e.Favicon("public/favicon.ico")

	e.Get("/", selfjs.New(runtime.NumCPU(), string(bundle), rss))
	e.Get("/about", selfjs.New(runtime.NumCPU(), string(bundle), loremJSON()))

	e.Get("/api/data", apiFrontPage)
	e.Get("/api/anotherpage", apiAnotherPage)
	go tick()
	fmt.Println("serving at port 3000")
	e.Run(":3000")
}
예제 #10
0
func loadHandlers(e *echo.Echo) {

	if itrak.Debug {
		e.SetDebug(true)
	}

	// Point to the client application generated inside the webapp dir
	e.Index("./webapp/build/index.html")
	e.ServeDir("/", "./webapp/build/")

	server_stats = stats.New()
	e.Use(server_stats.Handler)

	e.Get("/stats", getStats)
	e.Get("/test1", getTestData)
	e.Get("/part", getPartsList)
	e.Get("/task", getTaskList)
	e.Get("/jtask", getJTaskList)

	e.Post("/login", login)
	e.Delete("/login", logout)

	e.Get("/people", getPeople)
	e.Get("/people/:id", getPerson)
	e.Post("/people/:id", savePerson)

	e.Get("/site", getSites)
	e.Get("/site/:id", getSite)
	e.Post("/site/:id", saveSite)

	e.Get("/roles", getRoles)

	e.Get("/vendors", getAllVendors)
	e.Post("/vendors/:id", saveVendor)

	// Equipment Related functions
	e.Get("/equipment", getAllEquipment)
	e.Get("/site_equipment/:id", getAllSiteEquipment)
	e.Get("/equipment/:id", getEquipment)
	e.Post("/equipment/:id", saveEquipment)
	e.Get("/subparts/:id", subParts)
	e.Get("/spares", getAllSpares)
	e.Get("/spares/:id", getEquipment)
	e.Post("/spares/:id", saveEquipment)
	e.Get("/consumables", getAllConsumables)
	e.Get("/consumables/:id", getEquipment)
	e.Post("/consumables/:id", saveEquipment)

	e.Get("/equiptype", getAllEquipTypes)
	e.Get("/equiptype/:id", getEquipType)
	e.Post("/equiptype/:id", saveEquipType)

	e.Get("/task", getAllTask)
	e.Get("/sitetask/:id", getSiteTasks)
	e.Get("/task/:id", getTask)
	e.Post("/task/:id", saveTask)
}
예제 #11
0
파일: server.go 프로젝트: ch3lo/inspector
func main() {
	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte("{\"hello\": \"world\"}"))
	})

	handler := stats.New().Handler(h)
	http.ListenAndServe(":8080", handler)
}
예제 #12
0
func main() {
	fromEmail = os.Getenv("FROMEMAIL")
	emailSendingPasswd = os.Getenv("EMAILSENDINGPASSWD")
	if fromEmail == "" || emailSendingPasswd == "" {
		log.Fatal("FROMEMAIL or EMAILSENDINGPASSWD was not set")
	}
	runtime.GOMAXPROCS(runtime.NumCPU())
	app := NewApplication()
	app.Init()
	e := echo.New()

	e.Use(middleware.HttpLogger())
	e.HTTP2()
	e.SetHTTPErrorHandler(app.errorHandler)
	e.Use(mw.Recover())
	e.Use(mw.Gzip())
	e.StripTrailingSlash()
	e.Use(cors.Default().Handler)
	/* TODO: logs too much
	newrelickey, found := os.LookupEnv("NEWRELICKEY")
	if found == true {
		gorelic.InitNewRelicAgent(newrelickey, "go-register-login", true)
		e.Use(gorelic.Handler())
	}
	*/
	s := stats.New()
	e.Use(s.Handler)

	e.Get("/stats", func(c *echo.Context) error {
		return c.JSON(http.StatusOK, s.Data())
	})

	e.Favicon("public/favicon.ico")
	e.Static("/public/css", "public/css")
	e.Static("/universal.js", "./build/bundle.js")

	bundle, _ := ioutil.ReadFile("./build/bundle.js")
	user, _ := json.Marshal(domain.User{})

	e.Get("/", selfjs.New(runtime.NumCPU(), string(bundle), string(user)))
	e.Get("/register", selfjs.New(runtime.NumCPU(), string(bundle), string(user)))
	e.Get("/login", selfjs.New(runtime.NumCPU(), string(bundle), string(user)))

	admin := e.Group("/members")
	admin.Use(middleware.CheckAdmin(app.Redis, string(bundle)))
	admin.Get("", selfjs.New(runtime.NumCPU(), string(bundle), app.listUsers()))

	e.Get("/api/users", app.listUsersAPI)
	e.Get("/api/user/:id", app.userAPI)
	e.Get("/verify/:id/:hash", app.verifyEmail)
	e.Post("/register", app.createUser)
	e.Get("/logout", app.logout)
	e.Post("/login", app.login)
	fmt.Println("Starting server at port 3300")
	e.Run(":3300")
}
예제 #13
0
func getNegroniHandlers(ctx *RouterContext, router *mux.Router) []negroni.Handler {
	tmpArray := []negroni.Handler{}

	if frontendUrl := ctx.Settings.ServerFrontendUrl(); strings.TrimSpace(frontendUrl) != "" {
		tmpArray = append(tmpArray, cors.New(cors.Options{
			AllowedOrigins: []string{getBaseUrlWithoutSlash(frontendUrl)},
			AllowedHeaders: []string{"*"},
		}))
	}

	if ctx.Settings.IsDevMode() {
		tmpArray = append(tmpArray, NewAccessLoggingMiddleware(NewSimpleAccessInfoHandler(
			func(info *StartAccessInfo) {
				ctx.Logger.Debug(
					"START:     %s %s, RemAddr: %s, RemIP: %s, Proxies: %s",
					info.HttpMethod, info.RequestURI, info.RemoteAddr, info.RemoteIP, info.Proxies)
			},
			func(info *EndAccessInfo) {
				if !info.GotPanic {
					ctx.Logger.Debug(
						"END [OK]:  %s %s, Status: %d %s, Duration: %s",
						info.HttpMethod, info.RequestURI, info.Status, info.StatusText, info.Duration)
				} else {
					ctx.Logger.Debug(
						"END [ERR]: %s %s, Status: %d %s, Duration: %s",
						info.HttpMethod, info.RequestURI, info.Status, info.StatusText, info.Duration)
				}
			},
		)))

		middleware := stats.New()
		router.HandleFunc("/stats.json", func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/json")
			b, _ := json.Marshal(middleware.Data())
			w.Write(b)
		})
		tmpArray = append(tmpArray, middleware)
	}

	tmpArray = append(tmpArray, NewRecovery(func(errDetails *RecoveredErrorDetails) *RecoveryResponse {
		switch errObj := errDetails.OriginalError.(type) {
		case *ClientError:
			//No logging for this error, this is client side only
			return &RecoveryResponse{
				errObj.StatusCode,
				errObj.StatusText,
			}
		default:
			ctx.Logger.Error("ERROR recovered: %s\nStack:\n%s", errDetails.Error, errDetails.StackTrace)
			return nil
		}
	}))

	return tmpArray
}
예제 #14
0
파일: server.go 프로젝트: ch3lo/inspector
func main() {
	router := httprouter.New()
	s := stats.New()
	router.GET("/stats", func(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		s, err := json.Marshal(s.Data())
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
		w.Write(s)
	})
	http.ListenAndServe(":8080", s.Handler(router))
}
예제 #15
0
func main() {
	configtoml := flag.String("f", "moxy.toml", "Path to config. (default moxy.toml)")
	flag.Parse()
	file, err := ioutil.ReadFile(*configtoml)
	if err != nil {
		log.Fatal(err)
	}
	err = toml.Unmarshal(file, &config)
	if err != nil {
		log.Fatal("Problem parsing config: ", err)
	}
	if config.Statsd != "" {
		statsd, _ = g2s.Dial("udp", config.Statsd)
	}
	moxystats := stats.New()
	mux := http.NewServeMux()
	mux.HandleFunc("/moxy_callback", moxy_callback)
	mux.HandleFunc("/moxy_apps", moxy_apps)
	mux.HandleFunc("/moxy_stats", func(w http.ResponseWriter, req *http.Request) {
		if config.Xproxy != "" {
			w.Header().Add("X-Proxy", config.Xproxy)
		}
		stats := moxystats.Data()
		b, _ := json.MarshalIndent(stats, "", "  ")
		w.Write(b)
		return
	})
	mux.HandleFunc("/", moxy_proxy)
	// In case we want to log req/resp.
	//trace, _ := trace.New(redirect, os.Stdout)
	handler := moxystats.Handler(mux)
	s := &http.Server{
		Addr:    ":" + config.Port,
		Handler: handler,
	}
	callbackworker()
	callbackqueue <- true
	if config.TLS {
		log.Println("Starting moxy tls on :" + config.Port)
		err := s.ListenAndServeTLS(config.Cert, config.Key)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		log.Println("Starting moxy on :" + config.Port)
		err := s.ListenAndServe()
		if err != nil {
			log.Fatal(err)
		}
	}
}
예제 #16
0
func main() {
	middleware := stats.New()
	mux := http.NewServeMux()
	mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte("{\"hello\": \"world\"}"))
	})
	mux.HandleFunc("/stats", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		b, _ := json.Marshal(middleware.Data())
		w.Write(b)
	})
	http.ListenAndServe(":8080", middleware.Handler(mux))
}
예제 #17
0
func registerMiddleware(e *gin.Engine) {
	//------------------------
	// Third-party middleware
	//------------------------
	// See https://github.com/thoas/stats
	s := stats.New()
	e.Use(func(ctx *gin.Context) {
		beginning, recorder := s.Begin(ctx.Writer)
		ctx.Next()
		s.End(beginning, recorder)
	})
	// Route
	e.GET("/stats", func(c *gin.Context) {
		logger.Log.Info("In stats")
		c.JSON(http.StatusOK, s.Data())
	})
}
예제 #18
0
func main() {
	configtoml := flag.String("f", "nixy.toml", "Path to config. (default nixy.toml)")
	version := flag.Bool("v", false, "prints current nixy version")
	flag.Parse()
	if *version {
		fmt.Println(VERSION)
		os.Exit(0)
	}
	file, err := ioutil.ReadFile(*configtoml)
	if err != nil {
		log.Fatal(err)
	}
	err = toml.Unmarshal(file, &config)
	if err != nil {
		log.Fatal("Problem parsing config: ", err)
	}
	if config.Statsd != "" {
		statsd, _ = g2s.Dial("udp", config.Statsd)
	}
	nixystats := stats.New()
	//mux := http.NewServeMux()
	mux := mux.NewRouter()
	mux.HandleFunc("/", nixy_version)
	mux.HandleFunc("/v1/reload", nixy_reload)
	mux.HandleFunc("/v1/apps", nixy_apps)
	mux.HandleFunc("/v1/health", nixy_health)
	mux.HandleFunc("/v1/stats", func(w http.ResponseWriter, req *http.Request) {
		stats := nixystats.Data()
		b, _ := json.MarshalIndent(stats, "", "  ")
		w.Write(b)
		return
	})
	handler := nixystats.Handler(mux)
	s := &http.Server{
		Addr:    ":" + config.Port,
		Handler: handler,
	}
	eventStream()
	eventWorker()
	log.Println("Starting nixy on :" + config.Port)
	err = s.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}
예제 #19
0
func setupRouter(cfg func() *config.Config, logger func(interface{})) http.Handler {
	ourStats := stats.New()

	router := mux.NewRouter()
	router.HandleFunc("/", handlers.Root)
	router.HandleFunc("/experiments/", handlers.ListExperiments(cfg))
	router.HandleFunc("/groups/", handlers.ListGroups(cfg))
	router.HandleFunc("/features/", handlers.ListFeatures(cfg))
	router.HandleFunc("/participate/", handlers.Participate(cfg, logger))
	router.HandleFunc("/error/", func(w http.ResponseWriter, r *http.Request) { panic("error") })
	router.HandleFunc("/stats/", func(w http.ResponseWriter, r *http.Request) {
		b, _ := json.Marshal(ourStats.Data())
		w.Write(b)
	})

	return gorillahandlers.LoggingHandler(os.Stdout, handlers.ErrorHandler(
		ourStats.Handler(router)))
}
예제 #20
0
파일: server.go 프로젝트: ch3lo/inspector
func main() {
	middleware := stats.New()

	goji.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Write([]byte("{\"hello\": \"world\"}"))
	})
	goji.Get("/stats", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")

		stats := middleware.Data()

		b, _ := json.Marshal(stats)

		w.Write(b)
	})

	goji.Use(middleware.Handler)
	goji.Serve()
}
예제 #21
0
// NewContext builds a new Context instance
func NewContext() *Context {
	s := stats.New()

	r := render.New(render.Options{
		IsDevelopment: isDevEnv(),
		Funcs: []template.FuncMap{{
			"filterByNamespace":   api.FilterByNamespace,
			"filterByApplication": api.FilterByApplication,
			"filterByLabelValue":  api.FilterByLabelValue,
		}},
	})

	cacheEnabled := !isDevEnv()
	clientWrapper := api.NewClientWrapper(cacheEnabled)

	return &Context{
		ClientWrapper: clientWrapper,
		Render:        r,
		Stats:         s,
	}
}
예제 #22
0
파일: server.go 프로젝트: ch3lo/inspector
func Server(config Configuration) {
	corsMiddleware := cors.New(cors.Options{
		AllowedOrigins:   []string{"*"},
		AllowedMethods:   []string{"POST, GET, OPTIONS, PUT, DELETE, UPDATE"},
		AllowedHeaders:   []string{"Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"},
		ExposedHeaders:   []string{"Content-Length"},
		MaxAge:           50,
		AllowCredentials: true,
	})

	statsMiddleware := stats.New()

	router := routes(config, statsMiddleware)

	n := negroni.Classic()
	n.Use(corsMiddleware)
	n.Use(statsMiddleware)
	n.UseHandler(router)

	n.Run(":8080")
}
func main() {
	middleware := stats.New()
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page!")
	})

	mux.HandleFunc("/stats", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")

		stats := middleware.Data()

		b, _ := json.Marshal(stats)
		w.Write(b)
	})

	n := negroni.Classic()
	n.Use(middleware)
	n.UseHandler(mux)
	n.Run(":3000")
}
예제 #24
0
func main() {
	e := echo.New()

	// Enable colored log
	e.ColoredLog(true)

	// Middleware
	e.Use(mw.Logger())
	e.Use(mw.Recover())
	e.Use(mw.Gzip())

	// https://github.com/thoas/stats
	s := stats.New()
	e.Use(s.Handler)
	// Route
	e.Get("/stats", func(c *echo.Context) error {
		return c.JSON(http.StatusOK, s.Data())
	})

	// Serve index file
	e.Index("public/index.html")

	// Serve favicon
	e.Favicon("public/favicon.ico")

	// Serve static files
	e.Static("/scripts", "public/scripts")

	//-----------
	// Templates
	//-----------
	e.SetRenderer(controllers.CreateRenderer())
	e.Get("/page1", controllers.Page1Handler)
	e.Get("/page2", controllers.Page2Handler)

	// Start server
	log.Println("Server is starting for port 8080...")
	graceful.ListenAndServe(e.Server(":8080"), 2*time.Second)
	log.Println("Server stoped")
}
예제 #25
0
func main() {
	var err error
	globalData, err = LoadData()
	if err != nil {
		fmt.Println("data.json not found")
		panic(err)
	}
	go globalData.UpdateDB(false)

	e := echo.New()

	e.Use(mw.Logger())
	e.Use(mw.Recover())
	e.Use(mw.Gzip())

	// https://github.com/thoas/stats
	s := stats.New()
	e.Use(s.Handler)
	// Route
	e.Get("/stats", func(c *echo.Context) error {
		return c.JSON(http.StatusOK, s.Data())
	})

	e.Static("/css", "public/css")
	e.Static("/fonts", "public/fonts")
	e.Static("/img", "public/img")
	e.Static("/js", "public/js")

	t := &Template{
		templates: template.Must(template.ParseFiles("public/index.html")),
	}
	e.SetRenderer(t)
	e.Get("/update", update)
	e.Get("/raw", raw)
	e.Get("/", welcome)
	fmt.Println("starting on :80")
	go updateDB()
	// Start server
	e.Run(":80")
}
예제 #26
0
func main() {
	statsMiddleware := stats.New()
	c := cors.New(cors.Options{
		AllowedOrigins: []string{"http://foo.com"},
	})

	n := negroni.Classic()

	router := mux.NewRouter()
	apiRoutes := ApiRouter(statsMiddleware)

	router.HandleFunc("/", HomeHandler)
	router.PathPrefix("/api").Handler(negroni.New(
		statsMiddleware,
		negroni.Wrap(apiRoutes),
	))

	n.Use(c)
	n.UseHandler(router)
	n.Run("0.0.0.0:" + Port)

}
예제 #27
0
func initialize() *negroni.Negroni {
	vabanstats := stats.New()
	n := negroni.New(
		negroni.NewRecovery(),
		NewLogger(),
		xrequestid.New(8),
	)
	router := httprouter.New()
	router.GET("/", func(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
		stats := vabanstats.Data()
		r.JSON(w, http.StatusOK, stats)
	})
	router.GET("/v1/services", GetServices)
	router.GET("/v1/service/:service", GetService)
	router.GET("/v1/service/:service/ping", GetPing)
	router.GET("/v1/service/:service/health", GetHealth)
	router.GET("/v1/service/:service/health/:backend", GetHealth)
	router.POST("/v1/service/:service/health/:backend", PostHealth)
	router.POST("/v1/service/:service/ban", PostBan)
	// add router and clear mux.context values at the end of request life-times
	n.UseHandler(router)
	return n
}
예제 #28
0
파일: main.go 프로젝트: wishpond-dev/canoe
func main() {
	statsMiddleware := stats.New()

	router := mux.NewRouter()
	redirectionRouter := RedirectionRouter()
	apiRouter := ApiRouter(statsMiddleware)

	n := negroni.Classic()

	router.Host(redirectionHost()).Handler(negroni.New(
		statsMiddleware,
		negroni.Wrap(redirectionRouter),
	))

	router.Host(apiHost()).Handler(negroni.New(
		negroni.HandlerFunc(AuthenticateRequest),
		statsMiddleware,
		negroni.Wrap(apiRouter),
	))

	router.HandleFunc("/", HomeHandler)
	n.UseHandler(router)
	n.Run("0.0.0.0:" + runPort())
}
예제 #29
0
	"github.com/emilevauge/traefik/types"
	"github.com/gorilla/mux"
	"github.com/mailgun/manners"
	"github.com/mailgun/oxy/cbreaker"
	"github.com/mailgun/oxy/forward"
	"github.com/mailgun/oxy/roundrobin"
	"github.com/thoas/stats"
	"gopkg.in/alecthomas/kingpin.v2"
	"sync"
)

var (
	globalConfigFile      = kingpin.Arg("conf", "Main configration file.").Default("traefik.toml").String()
	version               = kingpin.Flag("version", "Get Version.").Short('v').Bool()
	currentConfigurations = make(configs)
	metrics               = stats.New()
	oxyLogger             = &OxyLogger{}
)

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	kingpin.Version(Version + " built on the " + BuildDate)
	kingpin.Parse()
	fmtlog.SetFlags(fmtlog.Lshortfile | fmtlog.LstdFlags)
	var srv *manners.GracefulServer
	var configurationRouter *mux.Router
	var configurationChan = make(chan types.ConfigMessage, 10)
	defer close(configurationChan)
	var configurationChanValidated = make(chan types.ConfigMessage, 10)
	defer close(configurationChanValidated)
	var sigs = make(chan os.Signal, 1)
예제 #30
0
파일: main.go 프로젝트: briandowns/raceway
func main() {
	flag.Parse()

	signal.Notify(signalsChan, os.Interrupt)

	go func() {
		for sig := range signalsChan {
			log.Printf("Exiting... %v\n", sig)
			signalsChan = nil
			os.Exit(1)
		}
	}()

	// don't go any further if no config is supplied
	if configFileFlag == "" {
		flag.Usage()
		os.Exit(1)
	}

	// Source in the configuration
	conf, err := config.Load(configFileFlag)
	if err != nil {
		log.Fatalln(err)
	}
	log.Printf("%+v\n", conf)
	// Start the scheduler
	scheduler.StartScheduler(conf)

	ren := render.New(render.Options{Layout: "layout"})

	store := cookiestore.New([]byte(uuid.NewUUID().String()))
	n := negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
		negroni.NewStatic(http.Dir("public")),
	)
	n.Use(sessions.Sessions("session", store))

	statsMiddleware := stats.New()

	router := mux.NewRouter()

	// Frontend
	router.HandleFunc(controllers.Frontend, controllers.FrontendHandler()).Methods("GET")

	// API routes
	router.HandleFunc(controllers.DeploymentsPath, controllers.DeploymentsHandler(ren, conf)).Methods("GET")

	router.HandleFunc(controllers.DeploymentsByNamePath, controllers.DeploymentsByNameHandler(ren, conf)).Methods("GET")

	router.HandleFunc(controllers.DeploymentsPath, controllers.NewDeploymentsHandler(ren, conf)).Methods("POST")

	router.HandleFunc(controllers.ScenariosPath, controllers.ScenariosHandler(ren, conf)).Methods("GET")

	router.HandleFunc(controllers.ScenariosByNamePath, controllers.ScenariosByNameHandler(ren, conf)).Methods("GET")

	router.HandleFunc(controllers.TasksPath, controllers.TasksHandler(ren, conf)).Methods("GET")

	router.HandleFunc(controllers.TasksResultPath, controllers.TasksResultsByUUIDHandler(ren, conf)).Methods("GET")

	router.HandleFunc(controllers.TasksByUUIDPath, controllers.TasksByUUIDHandler(ren, conf)).Methods("GET")

	router.HandleFunc(controllers.TasksRunningPath, controllers.TasksRunningHandler(ren, conf)).Methods("GET")

	router.HandleFunc(controllers.SchedulesPath, controllers.SchedulesHandler(ren, conf)).Methods("GET")

	router.HandleFunc(controllers.SchedulesByTaskUUIDPath, controllers.SchedulesByTaskIDHandler(ren, conf)).Methods("GET")

	router.HandleFunc(controllers.SchedulesPath, controllers.NewScheduleHandler(ren, conf)).Methods("POST")

	router.HandleFunc(controllers.SchedulesDeletePath, controllers.DeleteScheduleHandler(ren, conf)).Methods("DELETE")

	n.Use(statsMiddleware)
	n.UseHandler(router)
	n.Run(conf.Raceway.AppPort)
}