本文整理汇总了Golang中github.com/prometheus/client_golang/prometheus.InstrumentHandler函数的典型用法代码示例。如果您正苦于以下问题:Golang InstrumentHandler函数的具体用法?Golang InstrumentHandler怎么用?Golang InstrumentHandler使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了InstrumentHandler函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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))
}
示例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))
}
示例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)
}
示例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))
}
示例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
}
示例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(),
))
}
示例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))
}
示例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),
))
}
示例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)
}
示例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)
}
示例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)
}
示例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)
}
示例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
}
示例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
}
示例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)
}
}