本文整理汇总了Golang中github.com/prometheus/client_golang/prometheus.InstrumentHandler函数的典型用法代码示例。如果您正苦于以下问题:Golang InstrumentHandler函数的具体用法?Golang InstrumentHandler怎么用?Golang InstrumentHandler使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了InstrumentHandler函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: route
func (s *Server) route() {
s.r = mux.NewRouter().StrictSlash(true)
s.r.Path("/").Methods("OPTIONS").HandlerFunc(s.handleProbe)
s.r.Path("/robots.txt").HandlerFunc(s.handleRobotsTxt)
s.r.Path("/metrics").Handler(
prometheus.InstrumentHandler("metrics", prometheus.UninstrumentedHandler()))
s.r.PathPrefix("/static/").Handler(
prometheus.InstrumentHandler("static", http.StripPrefix("/static", http.HandlerFunc(s.handleStatic))))
s.r.Handle("/", prometheus.InstrumentHandlerFunc("home", s.handleHomeStatic))
s.r.PathPrefix("/about").Handler(
prometheus.InstrumentHandler("about", http.HandlerFunc(s.handleAboutStatic)))
s.r.HandleFunc("/room/{room:[a-z0-9]+}/ws", instrumentSocketHandlerFunc("ws", s.handleRoom))
s.r.Handle(
"/room/{room:[a-z0-9]+}/", prometheus.InstrumentHandlerFunc("room_static", s.handleRoomStatic))
s.r.Handle(
"/prefs/reset-password",
prometheus.InstrumentHandlerFunc("prefsResetPassword", s.handleResetPassword))
s.r.Handle(
"/prefs/verify", prometheus.InstrumentHandlerFunc("prefsVerify", s.handlePrefsVerify))
}
开发者ID:bramvdbogaerde,项目名称:heim,代码行数:25,代码来源:handlers.go
示例2: route
func (s *Server) route() {
s.r = mux.NewRouter().StrictSlash(true)
s.r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s.serveErrorPage("page not found", http.StatusNotFound, w, r)
})
s.r.Path("/").Methods("OPTIONS").HandlerFunc(s.handleProbe)
s.r.Path("/robots.txt").HandlerFunc(s.handleRobotsTxt)
s.r.Path("/metrics").Handler(
prometheus.InstrumentHandler("metrics", prometheus.UninstrumentedHandler()))
s.r.PathPrefix("/static/").Handler(
prometheus.InstrumentHandler("static", http.HandlerFunc(s.handleStatic)))
s.r.Handle("/", prometheus.InstrumentHandlerFunc("home", s.handleHomeStatic))
s.r.PathPrefix("/about").Handler(
prometheus.InstrumentHandler("about", http.HandlerFunc(s.handleAboutStatic)))
s.r.HandleFunc("/room/{prefix:(pm:)?}{room:[a-z0-9]+}/ws", instrumentSocketHandlerFunc("ws", s.handleRoom))
s.r.Handle(
"/room/{prefix:(pm:)?}{room:[a-z0-9]+}/", prometheus.InstrumentHandlerFunc("room_static", s.handleRoomStatic))
s.r.Handle(
"/prefs/reset-password",
prometheus.InstrumentHandlerFunc("prefsResetPassword", s.handlePrefsResetPassword))
s.r.Handle(
"/prefs/verify", prometheus.InstrumentHandlerFunc("prefsVerify", s.handlePrefsVerify))
}
开发者ID:logan,项目名称:heim,代码行数:29,代码来源:handlers.go
示例3: Start
func Start(config *Config) error {
if err := clone(config); err != nil {
return err
}
handler := handler(config)
ops := http.NewServeMux()
if config.AllowHooks {
ops.Handle("/hooks/", prometheus.InstrumentHandler("hooks", http.StripPrefix("/hooks", hooksHandler(config))))
}
/*ops.Handle("/reflect/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
fmt.Fprintf(os.Stdout, "%s %s\n", r.Method, r.URL)
io.Copy(os.Stdout, r.Body)
}))*/
ops.Handle("/metrics", prometheus.UninstrumentedHandler())
healthz.InstallHandler(ops)
mux := http.NewServeMux()
mux.Handle("/", prometheus.InstrumentHandler("git", handler))
mux.Handle("/_/", http.StripPrefix("/_", ops))
log.Printf("Serving %s on %s", config.Home, config.Listen)
return http.ListenAndServe(config.Listen, mux)
}
开发者ID:cjnygard,项目名称:origin,代码行数:25,代码来源:gitserver.go
示例4: Register
// Register the API's endpoints in the given router.
func (api *API) Register(r *route.Router) {
instr := func(name string, f apiFunc) http.HandlerFunc {
hf := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
setCORS(w)
if data, err := f(r); err != nil {
respondError(w, err, data)
} else if data != nil {
respond(w, data)
} else {
w.WriteHeader(http.StatusNoContent)
}
})
return prometheus.InstrumentHandler(name, httputil.CompressionHandler{
Handler: hf,
})
}
r.Options("/*path", instr("options", api.options))
r.Get("/query", instr("query", api.query))
r.Get("/query_range", instr("query_range", api.queryRange))
r.Get("/label/:name/values", instr("label_values", api.labelValues))
r.Get("/series", instr("series", api.series))
r.Del("/series", instr("drop_series", api.dropSeries))
}
开发者ID:brutus333,项目名称:prometheus,代码行数:28,代码来源:api.go
示例5: RegisterHttpHandler
// Register an endpoint with the HTTP server
func (m *Manager) RegisterHttpHandler(method string, path string, handle http.Handler) *Manager {
log.AppLog.Debug("Registering HTTP endpoint on '%s' with method '%s'", path, method)
m.httpRouter.Add(method, path, prometheus.InstrumentHandler(path, handle))
return m
}
开发者ID:nickwales,项目名称:proxym,代码行数:8,代码来源:manager.go
示例6: ExampleInstrumentHandler
func ExampleInstrumentHandler() {
// Handle the "/doc" endpoint with the standard http.FileServer handler.
// By wrapping the handler with InstrumentHandler, request count,
// request and response sizes, and request latency are automatically
// exported to Prometheus, partitioned by HTTP status code and method
// and by the handler name (here "fileserver").
http.Handle("/doc", prometheus.InstrumentHandler(
"fileserver", http.FileServer(http.Dir("/usr/share/doc")),
))
// The Prometheus handler still has to be registered to handle the
// "/metrics" endpoint. The handler returned by prometheus.Handler() is
// already instrumented - with "prometheus" as the handler name. In this
// example, we want the handler name to be "metrics", so we instrument
// the uninstrumented Prometheus handler ourselves.
http.Handle("/metrics", prometheus.InstrumentHandler(
"metrics", prometheus.UninstrumentedHandler(),
))
}
开发者ID:eghobo,项目名称:kubedash,代码行数:18,代码来源:examples_test.go
示例7: RegisterPublicDir
func (ah *apiHandler) RegisterPublicDir(mux *http.ServeMux) {
if ah.conf.PublicDir == "" {
return
}
fs := http.FileServer(http.Dir(ah.conf.PublicDir))
fs = prometheus.InstrumentHandler("frontend", fs)
prefix := ah.prefix("")
mux.Handle(prefix, http.StripPrefix(prefix, fs))
}
开发者ID:infertux,项目名称:freegeoip,代码行数:9,代码来源:http.go
示例8: RegisterHandler
// RegisterHandler registers the handler for the various endpoints below /api.
func (msrv *MetricsService) RegisterHandler() {
handler := func(h func(http.ResponseWriter, *http.Request)) http.Handler {
return httputils.CompressionHandler{
Handler: http.HandlerFunc(h),
}
}
http.Handle("/api/query", prometheus.InstrumentHandler(
"/api/query", handler(msrv.Query),
))
http.Handle("/api/query_range", prometheus.InstrumentHandler(
"/api/query_range", handler(msrv.QueryRange),
))
http.Handle("/api/metrics", prometheus.InstrumentHandler(
"/api/metrics", handler(msrv.Metrics),
))
http.Handle("/api/targets", prometheus.InstrumentHandler(
"/api/targets", handler(msrv.SetTargets),
))
}
开发者ID:gitlabuser,项目名称:prometheus,代码行数:20,代码来源:api.go
示例9: main
func main() {
flag.Parse()
store.Init()
p := func(name string, handler http.HandlerFunc) http.Handler {
return prometheus.InstrumentHandler(name, handler)
}
router := mux.NewRouter()
router.Handle("/metrics", prometheus.Handler())
router.Handle("/", p("/", home))
router.Handle("/login", p("/login", login))
router.Handle("/verify", p("/verify", verify))
apiRouter := mux.NewRouter()
apiRouter.Handle("/api/logout", p("/logout", logout))
apiRouter.Handle("/api/user", p("/user", user))
apiRouter.Handle("/api/user/project", p("/user/project", userProject))
apiRouter.Handle("/api/project", p("/project", project))
apiRouter.Handle("/api/project/member", p("/task/member", member))
apiRouter.Handle("/api/task", p("/task", task))
apiRouter.Handle("/api/task/worker", p("/task/worker", worker))
apiRouter.Handle("/api/milestone", p("/milestone", milestone))
apiRouter.Handle("/api/friend", p("/friend", friend))
apiRouter.Handle("/api/chat", p("/chat", chat))
apiRouter.HandleFunc("/api/ws", ws)
router.PathPrefix("/api").Handler(negroni.New(
negroni.HandlerFunc(apiMiddleware),
negroni.Wrap(apiRouter),
))
adminRouter := mux.NewRouter()
adminRouter.Handle("/api/admin/user", p("/admin/user", adminUser))
adminRouter.Handle("/api/admin/project", p("/admin/project", adminProject))
router.PathPrefix("/api/admin").Handler(negroni.New(
negroni.HandlerFunc(adminMiddleware),
negroni.Wrap(adminRouter),
))
go h.run()
n := negroni.Classic()
n.UseHandler(router)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
n.Run(":" + port)
}
开发者ID:bbh-labs,项目名称:openinnovation-old,代码行数:51,代码来源:main.go
示例10: ServeForever
func (w WebService) ServeForever(pathPrefix string) error {
http.Handle(pathPrefix+"favicon.ico", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "", 404)
}))
http.HandleFunc("/", prometheus.InstrumentHandlerFunc("index", func(rw http.ResponseWriter, req *http.Request) {
// The "/" pattern matches everything, so we need to check
// that we're at the root here.
if req.URL.Path == pathPrefix {
w.AlertsHandler.ServeHTTP(rw, req)
} else if req.URL.Path == strings.TrimRight(pathPrefix, "/") {
http.Redirect(rw, req, pathPrefix, http.StatusFound)
} else if !strings.HasPrefix(req.URL.Path, pathPrefix) {
// We're running under a prefix but the user requested something
// outside of it. Let's see if this page exists under the prefix.
http.Redirect(rw, req, pathPrefix+strings.TrimLeft(req.URL.Path, "/"), http.StatusFound)
} else {
http.NotFound(rw, req)
}
}))
http.Handle(pathPrefix+"alerts", prometheus.InstrumentHandler("alerts", w.AlertsHandler))
http.Handle(pathPrefix+"silences", prometheus.InstrumentHandler("silences", w.SilencesHandler))
http.Handle(pathPrefix+"status", prometheus.InstrumentHandler("status", w.StatusHandler))
http.Handle(pathPrefix+"metrics", prometheus.Handler())
if *useLocalAssets {
http.Handle(pathPrefix+"static/", http.StripPrefix(pathPrefix+"static/", http.FileServer(http.Dir("web/static"))))
} else {
http.Handle(pathPrefix+"static/", http.StripPrefix(pathPrefix+"static/", new(blob.Handler)))
}
http.Handle(pathPrefix+"api/", w.AlertManagerService.Handler())
log.Info("listening on ", *listenAddress)
return http.ListenAndServe(*listenAddress, nil)
}
开发者ID:tamsky,项目名称:alertmanager,代码行数:38,代码来源:web.go
示例11: ServeForever
// ServeForever serves the HTTP endpoints and only returns upon errors.
func (ws WebService) ServeForever() error {
http.Handle("/favicon.ico", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "", 404)
}))
http.Handle("/", prometheus.InstrumentHandler(
"/", ws.StatusHandler,
))
http.Handle("/alerts", prometheus.InstrumentHandler(
"/alerts", ws.AlertsHandler,
))
http.Handle("/consoles/", prometheus.InstrumentHandler(
"/consoles/", http.StripPrefix("/consoles/", ws.ConsolesHandler),
))
http.Handle("/graph", prometheus.InstrumentHandler(
"/graph", http.HandlerFunc(graphHandler),
))
http.Handle("/heap", prometheus.InstrumentHandler(
"/heap", http.HandlerFunc(dumpHeap),
))
ws.MetricsHandler.RegisterHandler()
http.Handle("/metrics", prometheus.Handler())
if *useLocalAssets {
http.Handle("/static/", prometheus.InstrumentHandler(
"/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("web/static"))),
))
} else {
http.Handle("/static/", prometheus.InstrumentHandler(
"/static/", http.StripPrefix("/static/", new(blob.Handler)),
))
}
if *userAssetsPath != "" {
http.Handle("/user/", prometheus.InstrumentHandler(
"/user/", http.StripPrefix("/user/", http.FileServer(http.Dir(*userAssetsPath))),
))
}
if *enableQuit {
http.Handle("/-/quit", http.HandlerFunc(ws.quitHandler))
}
glog.Info("listening on ", *listenAddress)
return http.ListenAndServe(*listenAddress, nil)
}
开发者ID:gitlabuser,项目名称:prometheus,代码行数:48,代码来源:web.go
示例12: RegisterEncoder
func (ah *apiHandler) RegisterEncoder(mux *http.ServeMux, path string, enc freegeoip.Encoder) {
f := http.Handler(freegeoip.NewHandler(ah.conf.DB, enc))
if ah.conf.RateLimiter.Max > 0 {
rl := ah.conf.RateLimiter
rl.Handler = f
f = &rl
}
origin := ah.conf.Origin
if origin == "" {
origin = "*"
}
f = cors(f, origin, "GET", "HEAD")
f = prometheus.InstrumentHandler(path, f)
mux.Handle(ah.prefix(path), f)
}
开发者ID:JohnnyLe,项目名称:freegeoip,代码行数:15,代码来源:http.go
示例13: configureRouter
func (s *Server) configureRouter() error {
dirs := s.conf.GetDirectives()
router := mux.NewRouter()
// register prometheus handler
router.Handle("/metrics", prometheus.Handler())
services, err := getServices(s.conf)
if err != nil {
return err
}
corsEnabled := dirs.Server.CORSEnabledServices
base := strings.TrimRight(dirs.Server.BaseURL, "/")
for _, svc := range services {
for path, methods := range svc.Endpoints() {
for method, handlerFunc := range methods {
handlerFunc := http.HandlerFunc(handlerFunc)
var handler http.Handler
handler = handlerFunc
if isServiceEnabled(svc.Name(), corsEnabled) {
handler = s.corsHandler(handlerFunc)
}
svcBase := strings.TrimRight(svc.BaseURL(), "/")
fullEndpoint := base + svcBase + path
router.Handle(fullEndpoint, handler).Methods(method)
if isServiceEnabled(svc.Name(), corsEnabled) {
router.Handle(fullEndpoint, handler).Methods("OPTIONS")
}
u := strings.TrimRight(dirs.Server.BaseURL, "/") + svcBase + path
prometheus.InstrumentHandler(u, handler)
//ep := fmt.Sprintf("%s %s", method, u)
s.log.WithField("method", method).WithField("endpoint", u).Info("endpoint registered")
if isServiceEnabled(svc.Name(), corsEnabled) {
//ep := fmt.Sprintf("%s %s", "OPTIONS", u)
s.log.WithField("method", "OPTIONS").WithField("endpoint", u).Info("endpoint registered (cors)")
}
}
}
}
s.router = router
return nil
}
开发者ID:clawio,项目名称:clawiod,代码行数:48,代码来源:server.go
示例14: Create
// Create is used to create a new router
func Create(scheduler types.Scheduler) *mux.Router {
routes := types.Routes{
types.Route{
Name: "AddTask",
Method: "POST",
Pattern: "/task",
Handler: handler.AddTask(scheduler),
},
types.Route{
Name: "Status",
Method: "GET",
Pattern: "/task/{taskId}",
Handler: handler.GetTaskInfo(scheduler),
},
}
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(prometheus.InstrumentHandler(route.Name, route.Handler))
}
router.
Methods("GET").
Path("/metrics").
Name("Metrics").
Handler(prometheus.Handler())
router.
Methods("GET").
Path("/").
Name("Index").
HandlerFunc(indexHandler)
router.PathPrefix("/static/").
Handler(
http.StripPrefix(
"/static/", http.FileServer(
&assetfs.AssetFS{Asset: assets.Asset, AssetDir: assets.AssetDir, AssetInfo: assets.AssetInfo, Prefix: "static"})))
router.NotFoundHandler = http.HandlerFunc(notFound)
return router
}
开发者ID:keis,项目名称:eremetic,代码行数:48,代码来源:routes.go
示例15: main
func main() {
logger := log.NewJSONLogger(os.Stdout)
listen := os.Getenv("VANITY_LISTEN")
if listen == "" {
listen = ":8080"
}
listenMgmt := os.Getenv("VANITY_LISTEN_MGMT")
if listenMgmt == "" {
listenMgmt = ":8081"
}
config, err := loadConfiguration(logger, "conf/vanity.yaml")
if err != nil {
logger.Log("level", "error", "msg", "Could not load config", "err", err)
os.Exit(1)
}
srv := server.New(server.Config{
Log: logger,
Hosts: config.Hosts,
})
go handleSigs()
go func() {
http.Handle("/metrics", prometheus.Handler())
http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "OK", http.StatusOK)
})
http.HandleFunc("/", http.NotFound)
if err := http.ListenAndServe(listenMgmt, nil); err != nil {
logger.Log("level", "error", "msg", "Failed to listen on management port", "err", err)
}
}()
s := &http.Server{
Addr: listen,
Handler: prometheus.InstrumentHandler("vanity", srv),
}
if err := s.ListenAndServe(); err != nil {
logger.Log("level", "error", "msg", "Failed to listen", "err", err)
os.Exit(1)
}
}
开发者ID:dominikschulz,项目名称:vanity,代码行数:45,代码来源:main.go
示例16: NewRouter
// NewRouter is used to create a new router.
func NewRouter(scheduler eremetic.Scheduler, conf *config.Config, db eremetic.TaskDB) *mux.Router {
h := NewHandler(scheduler, db)
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes(h, conf) {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(prometheus.InstrumentHandler(route.Name, route.Handler))
}
router.
PathPrefix("/static/").
Handler(h.StaticAssets())
router.NotFoundHandler = http.HandlerFunc(h.NotFound())
return router
}
开发者ID:klarna,项目名称:eremetic,代码行数:21,代码来源:routes.go
示例17: publicDir
func (f *apiHandler) publicDir() http.HandlerFunc {
fs := http.FileServer(http.Dir(f.conf.PublicDir))
return prometheus.InstrumentHandler("frontend", fs)
}
开发者ID:mathieu-aubin,项目名称:freegeoip,代码行数:4,代码来源:api.go
示例18: register
func (f *apiHandler) register(name string, writer writerFunc) http.HandlerFunc {
h := prometheus.InstrumentHandler(name, f.iplookup(writer))
return f.cors.Handler(h).ServeHTTP
}
开发者ID:mathieu-aubin,项目名称:freegeoip,代码行数:4,代码来源:api.go
示例19: handle
func handle(name string, f http.HandlerFunc) http.HandlerFunc {
h := httputil.CompressionHandler{
Handler: f,
}
return prometheus.InstrumentHandler(name, h)
}
开发者ID:hvnsweeting,项目名称:prometheus,代码行数:6,代码来源:api.go
示例20: testHandler
//.........这里部分代码省略.........
headers: map[string]string{
"Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=text;q=0.5, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.4",
},
out: output{
headers: map[string]string{
"Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=text`,
},
body: bytes.Join(
[][]byte{
externalMetricFamilyAsProtoText,
expectedMetricFamilyAsProtoText,
},
[]byte{},
),
},
collector: metricVec,
externalMF: []*dto.MetricFamily{externalMetricFamily},
},
{ // 14
headers: map[string]string{
"Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text",
},
out: output{
headers: map[string]string{
"Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text`,
},
body: bytes.Join(
[][]byte{
externalMetricFamilyAsProtoCompactText,
expectedMetricFamilyAsProtoCompactText,
},
[]byte{},
),
},
collector: metricVec,
externalMF: []*dto.MetricFamily{externalMetricFamily},
},
{ // 15
headers: map[string]string{
"Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text",
},
out: output{
headers: map[string]string{
"Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text`,
},
body: bytes.Join(
[][]byte{
externalMetricFamilyAsProtoCompactText,
expectedMetricFamilyMergedWithExternalAsProtoCompactText,
},
[]byte{},
),
},
collector: metricVec,
externalMF: []*dto.MetricFamily{
externalMetricFamily,
externalMetricFamilyWithSameName,
},
},
}
for i, scenario := range scenarios {
registry := prometheus.NewPedanticRegistry()
gatherer := prometheus.Gatherer(registry)
if scenario.externalMF != nil {
gatherer = prometheus.Gatherers{
registry,
prometheus.GathererFunc(func() ([]*dto.MetricFamily, error) {
return scenario.externalMF, nil
}),
}
}
if scenario.collector != nil {
registry.Register(scenario.collector)
}
writer := httptest.NewRecorder()
handler := prometheus.InstrumentHandler("prometheus", promhttp.HandlerFor(gatherer, promhttp.HandlerOpts{}))
request, _ := http.NewRequest("GET", "/", nil)
for key, value := range scenario.headers {
request.Header.Add(key, value)
}
handler(writer, request)
for key, value := range scenario.out.headers {
if writer.HeaderMap.Get(key) != value {
t.Errorf(
"%d. expected %q for header %q, got %q",
i, value, key, writer.Header().Get(key),
)
}
}
if !bytes.Equal(scenario.out.body, writer.Body.Bytes()) {
t.Errorf(
"%d. expected body:\n%s\ngot body:\n%s\n",
i, scenario.out.body, writer.Body.Bytes(),
)
}
}
}
开发者ID:Griesbacher,项目名称:nagflux,代码行数:101,代码来源:registry_test.go
注:本文中的github.com/prometheus/client_golang/prometheus.InstrumentHandler函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论