本文整理汇总了Golang中github.com/thoas/stats.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: NewGlobals
func NewGlobals() *Globals {
globals := &Globals{}
globals.confFilename = *configFilename
globals.ReloadConfig()
globals.StatsServer = stats.New()
globals.StatsAdmin = stats.New()
return globals
}
开发者ID:KarolBedkowski,项目名称:secproxy,代码行数:8,代码来源:globals.go
示例2: getNegroniHandlers
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
}
开发者ID:francoishill,项目名称:windows-startup-manager,代码行数:27,代码来源:server.go
示例3: main
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")
}
开发者ID:blebougge,项目名称:go-rest-api-template,代码行数:29,代码来源:main.go
示例4: NewWebService
// 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
}
开发者ID:riseofthetigers,项目名称:service,代码行数:27,代码来源:service.go
示例5: Handler
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
}
开发者ID:kerkerj,项目名称:gtg15-demo,代码行数:35,代码来源:api.go
示例6: main
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()
}
开发者ID:ch3lo,项目名称:inspector,代码行数:27,代码来源:server.go
示例7: main
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"))
}
开发者ID:plumbum,项目名称:go-samples,代码行数:31,代码来源:main.go
示例8: main
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")
}
开发者ID:jelinden,项目名称:go-isomorphic-react-v8,代码行数:33,代码来源:main.go
示例9: loadHandlers
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)
}
开发者ID:steveoc64,项目名称:itrak.mmaint,代码行数:57,代码来源:handlers.go
示例10: main
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")
}
开发者ID:JC1738,项目名称:go-react-seed,代码行数:56,代码来源:server.go
示例11: getNegroniHandlers
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
}
开发者ID:grkg8tr,项目名称:generator-aurelia-auth-go,代码行数:55,代码来源:server.go
示例12: main
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)
}
}
}
开发者ID:abhishekamralkar,项目名称:moxy,代码行数:51,代码来源:moxy.go
示例13: main
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))
}
开发者ID:otsimo,项目名称:distribution,代码行数:14,代码来源:server.go
示例14: registerMiddleware
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())
})
}
开发者ID:mitre,项目名称:ptmatch,代码行数:17,代码来源:server_setup.go
示例15: main
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)
}
}
开发者ID:abhishekamralkar,项目名称:nixy,代码行数:45,代码来源:nixy.go
示例16: setupRouter
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)))
}
开发者ID:robinedwards,项目名称:bouncer,代码行数:18,代码来源:main.go
示例17: NewContext
// 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,
}
}
开发者ID:vbehar,项目名称:openshift-dashboard,代码行数:22,代码来源:context.go
示例18: Server
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")
}
开发者ID:ch3lo,项目名称:inspector,代码行数:21,代码来源:server.go
示例19: main
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")
}
开发者ID:jameshwang,项目名称:100_golang_projects_challenge,代码行数:21,代码来源:main.go
示例20: main
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")
}
开发者ID:amsokol,项目名称:sti-labs-golang1,代码行数:40,代码来源:main.go
注:本文中的github.com/thoas/stats.New函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论