本文整理汇总了Golang中github.com/prometheus/client_golang/prometheus.Handler函数的典型用法代码示例。如果您正苦于以下问题:Golang Handler函数的具体用法?Golang Handler怎么用?Golang Handler使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Handler函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: Serve
func Serve(ctx scope.Context, addr string) {
http.Handle("/metrics", prometheus.Handler())
listener, err := net.Listen("tcp", addr)
if err != nil {
ctx.Terminate(err)
}
closed := false
m := sync.Mutex{}
closeListener := func() {
m.Lock()
if !closed {
listener.Close()
closed = true
}
m.Unlock()
}
// Spin off goroutine to watch ctx and close listener if shutdown requested.
go func() {
<-ctx.Done()
closeListener()
}()
if err := http.Serve(listener, nil); err != nil {
fmt.Printf("http[%s]: %s\n", addr, err)
ctx.Terminate(err)
}
closeListener()
ctx.WaitGroup().Done()
}
开发者ID:logan,项目名称:heim,代码行数:33,代码来源:server.go
示例2: main
func main() {
flag.Parse()
manager := newDockerManager(*addr, *parent)
var labels []string
if *labelString != "" {
labels = strings.Split(*labelString, ",")
} else {
labels = make([]string, 0)
}
dockerClient, err := docker.NewClient("unix:///var/run/docker.sock")
if err != nil {
log.Fatalf("Unable to start docker client %v", err.Error())
}
exporter := NewExporter(manager, *dockerClient, labels)
prometheus.MustRegister(exporter)
log.Printf("Starting Server: %s", *listeningAddress)
handler := prometheus.Handler()
if *authUser != "" || *authPass != "" {
if *authUser == "" || *authPass == "" {
glog.Fatal("You need to specify -auth.user and -auth.pass to enable basic auth")
}
handler = &basicAuthHandler{
handler: prometheus.Handler().ServeHTTP,
user: *authUser,
password: *authPass,
}
}
http.Handle(*metricsEndpoint, handler)
log.Fatal(http.ListenAndServe(*listeningAddress, nil))
}
开发者ID:yanghongkjxy,项目名称:container_exporter,代码行数:32,代码来源:main.go
示例3: main
func main() {
flag.Parse()
dsn := os.Getenv("DATA_SOURCE_NAME")
if len(dsn) == 0 {
log.Fatal("couldn't find environment variable DATA_SOURCE_NAME")
}
exporter := NewExporter(dsn)
prometheus.MustRegister(exporter)
handler := prometheus.Handler()
if *authUser != "" || *authPass != "" {
if *authUser == "" || *authPass == "" {
log.Fatal("You need to specify -auth.user and -auth.pass to enable basic auth")
}
handler = &basicAuthHandler{
handler: prometheus.Handler().ServeHTTP,
user: *authUser,
password: *authPass,
}
}
http.Handle(*metricPath, handler)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write(landingPage)
})
log.Infof("Starting Server: %s", *listenAddress)
log.Fatal(http.ListenAndServe(*listenAddress, nil))
}
开发者ID:afefelov,项目名称:postgres_exporter,代码行数:30,代码来源:postgres_exporter.go
示例4: main
func main() {
flag.Parse()
if *printCollectors {
collectorNames := make(sort.StringSlice, 0, len(collector.Factories))
for n := range collector.Factories {
collectorNames = append(collectorNames, n)
}
collectorNames.Sort()
fmt.Printf("Available collectors:\n")
for _, n := range collectorNames {
fmt.Printf(" - %s\n", n)
}
return
}
collectors, err := loadCollectors()
if err != nil {
log.Fatalf("Couldn't load collectors: %s", err)
}
log.Infof("Enabled collectors:")
for n := range collectors {
log.Infof(" - %s", n)
}
nodeCollector := NodeCollector{collectors: collectors}
prometheus.MustRegister(nodeCollector)
sigUsr1 := make(chan os.Signal)
signal.Notify(sigUsr1, syscall.SIGUSR1)
handler := prometheus.Handler()
if *authUser != "" || *authPass != "" {
if *authUser == "" || *authPass == "" {
log.Fatal("You need to specify -auth.user and -auth.pass to enable basic auth")
}
handler = &basicAuthHandler{
handler: prometheus.Handler().ServeHTTP,
user: *authUser,
password: *authPass,
}
}
http.Handle(*metricsPath, handler)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>Node Exporter</title></head>
<body>
<h1>Node Exporter</h1>
<p><a href="` + *metricsPath + `">Metrics</a></p>
</body>
</html>`))
})
log.Infof("Starting node_exporter v%s at %s", Version, *listenAddress)
err = http.ListenAndServe(*listenAddress, nil)
if err != nil {
log.Fatal(err)
}
}
开发者ID:ra1fh,项目名称:node_exporter,代码行数:60,代码来源:node_exporter.go
示例5: main
func main() {
flag.Parse()
log.SetFlags(log.LstdFlags | log.Lshortfile)
prometheus.MustRegister(&mPowerCollector{})
http.Handle("/metrics", prometheus.Handler())
http.ListenAndServe(*addr, prometheus.Handler())
}
开发者ID:swsnider,项目名称:mpower_exporter,代码行数:9,代码来源:main.go
示例6: prometheusHandler
func prometheusHandler() http.Handler {
handler := prometheus.Handler()
if hasUserAndPassword() {
handler = &basicAuthHandler{
handler: prometheus.Handler().ServeHTTP,
user: *authUserFlag,
password: *authPassFlag,
}
}
return handler
}
开发者ID:jasson15,项目名称:mongodb_exporter,代码行数:12,代码来源:mongodb_exporter.go
示例7: main
func main() {
flag.Parse()
// seed the RNG, otherwise we would have same randomness on every startup
// which should not, but might in worst case interfere with leftover-mails
// from earlier starts of the binary
rand.Seed(time.Now().Unix())
err := parse_conf(*conf_path)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
wg := new(sync.WaitGroup)
wg.Add(len(globalconf.Servers))
// now fire up the monitoring jobs
for _, c := range globalconf.Servers {
fmt.Println("starting monitoring for config", c["Name"])
go monitor(c, wg)
// keep a timedelta between monitoring jobs to avoid strong interference
time.Sleep(startupOffsetTime)
}
fmt.Println("starting HTTP-endpoint")
if *useAuth {
authenticator := auth.NewBasicAuthenticator("prometheus", Secret)
http.HandleFunc(globalconf.Http_endpoint, auth.JustCheck(authenticator, prometheus.Handler().ServeHTTP))
} else {
http.Handle(globalconf.Http_endpoint, prometheus.Handler())
}
if *useTLS {
err = http.ListenAndServeTLS(":"+globalconf.Http_port, globalconf.Crt_path, globalconf.Key_path, nil)
} else {
err = http.ListenAndServe(":"+globalconf.Http_port, nil)
}
if err != nil {
fmt.Println(err)
}
// wait for goroutines to exit
// otherwise main would terminate and the goroutines monitoring would be killed
wg.Wait()
}
开发者ID:brian-brazil,项目名称:mailexporter,代码行数:51,代码来源:mailexporter.go
示例8: RegisterHandlers
func RegisterHandlers(mux httpMux.Mux, containerManager manager.Manager, httpAuthFile, httpAuthRealm, httpDigestFile, httpDigestRealm, prometheusEndpoint string) error {
// Basic health handler.
if err := healthz.RegisterHandler(mux); err != nil {
return fmt.Errorf("failed to register healthz handler: %s", err)
}
// Validation/Debug handler.
mux.HandleFunc(validate.ValidatePage, func(w http.ResponseWriter, r *http.Request) {
err := validate.HandleRequest(w, containerManager)
if err != nil {
fmt.Fprintf(w, "%s", err)
}
})
// Register API handler.
if err := api.RegisterHandlers(mux, containerManager); err != nil {
return fmt.Errorf("failed to register API handlers: %s", err)
}
// Redirect / to containers page.
mux.Handle("/", http.RedirectHandler(pages.ContainersPage, http.StatusTemporaryRedirect))
var authenticated bool = false
// Setup the authenticator object
if httpAuthFile != "" {
glog.Infof("Using auth file %s", httpAuthFile)
secrets := auth.HtpasswdFileProvider(httpAuthFile)
authenticator := auth.NewBasicAuthenticator(httpAuthRealm, secrets)
mux.HandleFunc(static.StaticResource, authenticator.Wrap(staticHandler))
if err := pages.RegisterHandlersBasic(mux, containerManager, authenticator); err != nil {
return fmt.Errorf("failed to register pages auth handlers: %s", err)
}
authenticated = true
}
if httpAuthFile == "" && httpDigestFile != "" {
glog.Infof("Using digest file %s", httpDigestFile)
secrets := auth.HtdigestFileProvider(httpDigestFile)
authenticator := auth.NewDigestAuthenticator(httpDigestRealm, secrets)
mux.HandleFunc(static.StaticResource, authenticator.Wrap(staticHandler))
if err := pages.RegisterHandlersDigest(mux, containerManager, authenticator); err != nil {
return fmt.Errorf("failed to register pages digest handlers: %s", err)
}
authenticated = true
}
// Change handler based on authenticator initalization
if !authenticated {
mux.HandleFunc(static.StaticResource, staticHandlerNoAuth)
if err := pages.RegisterHandlersBasic(mux, containerManager, nil); err != nil {
return fmt.Errorf("failed to register pages handlers: %s", err)
}
}
collector := metrics.NewPrometheusCollector(containerManager)
prometheus.MustRegister(collector)
http.Handle(prometheusEndpoint, prometheus.Handler())
return nil
}
开发者ID:alena1108,项目名称:kubernetes,代码行数:60,代码来源:handlers.go
示例9: main
func main() {
flag.Parse()
rand.Seed(time.Now().UnixNano())
fmt.Println("Debian Code Search source-backend")
listener, err := net.Listen("tcp", *listenAddressStreaming)
if err != nil {
log.Fatal(err)
}
go func() {
for {
conn, err := listener.Accept()
if err != nil {
log.Fatalf("Error accepting session: %v", err)
}
go streamingQuery(conn)
}
}()
http.HandleFunc("/file", File)
http.Handle("/metrics", prometheus.Handler())
log.Fatal(http.ListenAndServe(*listenAddress, nil))
}
开发者ID:jamessan,项目名称:dcs,代码行数:25,代码来源:source-backend.go
示例10: InstallDefaultHandlers
// InstallDefaultHandlers registers the default set of supported HTTP request
// patterns with the restful Container.
func (s *Server) InstallDefaultHandlers() {
healthz.InstallHandler(s.restfulCont,
healthz.PingHealthz,
healthz.NamedCheck("syncloop", s.syncLoopHealthCheck),
)
var ws *restful.WebService
ws = new(restful.WebService)
ws.
Path("/pods").
Produces(restful.MIME_JSON)
ws.Route(ws.GET("").
To(s.getPods).
Operation("getPods"))
s.restfulCont.Add(ws)
s.restfulCont.Handle("/stats/", &httpHandler{f: s.handleStats})
s.restfulCont.Handle("/metrics", prometheus.Handler())
ws = new(restful.WebService)
ws.
Path("/spec/").
Produces(restful.MIME_JSON)
ws.Route(ws.GET("").
To(s.getSpec).
Operation("getSpec").
Writes(cadvisorapi.MachineInfo{}))
s.restfulCont.Add(ws)
}
开发者ID:fwalker,项目名称:dashboard,代码行数:30,代码来源:server.go
示例11: RegisterWeb
// RegisterWeb registers handlers to serve files for the web interface.
func RegisterWeb(r *route.Router, reloadCh chan<- struct{}) {
ihf := prometheus.InstrumentHandlerFunc
r.Get("/app/*filepath", ihf("app_files",
func(w http.ResponseWriter, req *http.Request) {
fp := route.Param(route.Context(req), "filepath")
serveAsset(w, req, filepath.Join("ui/app", fp))
},
))
r.Get("/lib/*filepath", ihf("lib_files",
func(w http.ResponseWriter, req *http.Request) {
fp := route.Param(route.Context(req), "filepath")
serveAsset(w, req, filepath.Join("ui/lib", fp))
},
))
r.Get("/metrics", prometheus.Handler().ServeHTTP)
r.Get("/", ihf("index", func(w http.ResponseWriter, req *http.Request) {
serveAsset(w, req, "ui/app/index.html")
}))
r.Post("/-/reload", func(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("Reloading configuration file..."))
reloadCh <- struct{}{}
})
r.Get("/debug/*subpath", http.DefaultServeMux.ServeHTTP)
r.Post("/debug/*subpath", http.DefaultServeMux.ServeHTTP)
}
开发者ID:yacloud-io,项目名称:alertmanager,代码行数:31,代码来源:web.go
示例12: main
func main() {
flag.Parse()
http.HandleFunc("/favicon.ico", http.NotFound)
http.HandleFunc("/hi", handleHi)
http.Handle("/metrics", prometheus.Handler())
log.Fatal(http.ListenAndServe(":"+*port, nil))
}
开发者ID:jaqx0r,项目名称:blts,代码行数:7,代码来源:s.go
示例13: main
func main() {
var (
listen = flag.String("listen", ":7800", "Server listen address.")
name = flag.String("test.name", "unknown", "Name of the test to run.")
path = flag.String("test.path", "/", "Path to hit on the targets")
rate = flag.Uint64("test.rate", defaultRate, "Number of requests to send during test duration.")
timeout = flag.Duration("test.timeout", defaultTimeout, "Time until a request is discarded")
ts = targets{}
)
flag.Var(&ts, "test.target", `Target to hit by the test with the following format: -test.target="NAME:address/url"`)
flag.Parse()
if *listen == "" || len(ts) == 0 {
flag.Usage()
os.Exit(1)
}
var (
test = newTest(*name, *path, *rate, defaultInterval, *timeout, ts)
registry = newRegistry(prometheus.Labels{"test": test.name})
resultc = make(chan result)
)
test.run(resultc)
go registry.collect(resultc)
http.Handle("/metrics", prometheus.Handler())
log.Printf("Starting server on %s", *listen)
log.Fatal(http.ListenAndServe(*listen, nil))
}
开发者ID:leochencipher,项目名称:eagle,代码行数:32,代码来源:eagle.go
示例14: setupMetrics
func setupMetrics(ctx *grader.Context) {
for _, gauge := range gauges {
prometheus.MustRegister(gauge)
}
for _, counter := range counters {
prometheus.MustRegister(counter)
}
for _, summary := range summaries {
prometheus.MustRegister(summary)
}
metricsMux := http.NewServeMux()
metricsMux.Handle("/metrics", prometheus.Handler())
go func() {
addr := fmt.Sprintf(":%d", ctx.Config.Metrics.Port)
ctx.Log.Error(
"http listen and serve",
"err", http.ListenAndServe(addr, metricsMux),
)
}()
go func() {
gaugesUpdate()
time.Sleep(time.Duration(1) * time.Minute)
}()
}
开发者ID:lhchavez,项目名称:quark,代码行数:25,代码来源:metrics.go
示例15: main
func main() {
flag.Parse()
yamlFile, err := ioutil.ReadFile(*configFile)
if err != nil {
log.Fatalf("Error reading config file: %s", err)
}
config := Config{}
err = yaml.Unmarshal(yamlFile, &config)
if err != nil {
log.Fatalf("Error parsing config file: %s", err)
}
http.Handle("/metrics", prometheus.Handler())
http.HandleFunc("/probe",
func(w http.ResponseWriter, r *http.Request) {
probeHandler(w, r, &config)
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>Blackbox Exporter</title></head>
<body>
<h1>Blackbox Exporter</h1>
<p><a href="/probe?target=prometheus.io&module=http_2xx">Probe prometheus.io for http_2xx</a></p>
<p><a href="/metrics">Metrics</a></p>
</body>
</html>`))
})
if err := http.ListenAndServe(*addr, nil); err != nil {
log.Fatalf("Error starting HTTP server: %s", err)
}
}
开发者ID:flecno,项目名称:blackbox_exporter,代码行数:35,代码来源:main.go
示例16: startStatusHTTP
func (s *Server) startStatusHTTP() {
once.Do(func() {
go func() {
http.HandleFunc("/status", func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
s := status{
Connections: s.ConnectionCount(),
Version: mysql.ServerVersion,
GitHash: printer.TiDBGitHash,
}
js, err := json.Marshal(s)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Error("Encode json error", err)
} else {
w.Write(js)
}
})
// HTTP path for prometheus.
http.Handle("/metrics", prometheus.Handler())
addr := s.cfg.StatusAddr
if len(addr) == 0 {
addr = defaultStatusAddr
}
log.Infof("Listening on %v for status and metrics report.", addr)
err := http.ListenAndServe(addr, nil)
if err != nil {
log.Fatal(err)
}
}()
})
}
开发者ID:pingcap,项目名称:tidb,代码行数:33,代码来源:server.go
示例17: main
func main() {
go DockerCollection()
http.Handle("/metrics", prometheus.Handler())
http.ListenAndServe(":7890", nil)
}
开发者ID:hatchan,项目名称:docker-monitor,代码行数:7,代码来源:main.go
示例18: RootHandler
// RootHandler returns the handler that routes all the paths from / for the
// server.
func RootHandler(ac auth.AccessController, ctx context.Context, trust signed.CryptoService) http.Handler {
hand := utils.RootHandlerFactory(ac, ctx, trust)
r := mux.NewRouter()
r.Methods("GET").Path("/v2/").Handler(hand(handlers.MainHandler))
r.Methods("POST").Path("/v2/{imageName:.*}/_trust/tuf/").Handler(
prometheus.InstrumentHandlerWithOpts(
prometheusOpts("UpdateTuf"),
hand(handlers.AtomicUpdateHandler, "push", "pull")))
r.Methods("GET").Path("/v2/{imageName:.*}/_trust/tuf/{tufRole:root|targets(?:/[^/\\s]+)*|snapshot|timestamp}.{checksum:[a-fA-F0-9]{64}|[a-fA-F0-9]{96}|[a-fA-F0-9]{128}}.json").Handler(
prometheus.InstrumentHandlerWithOpts(
prometheusOpts("GetRoleByHash"),
hand(handlers.GetHandler, "pull")))
r.Methods("GET").Path("/v2/{imageName:.*}/_trust/tuf/{tufRole:root|targets(?:/[^/\\s]+)*|snapshot|timestamp}.json").Handler(
prometheus.InstrumentHandlerWithOpts(
prometheusOpts("GetRole"),
hand(handlers.GetHandler, "pull")))
r.Methods("GET").Path(
"/v2/{imageName:.*}/_trust/tuf/{tufRole:snapshot|timestamp}.key").Handler(
prometheus.InstrumentHandlerWithOpts(
prometheusOpts("GetKey"),
hand(handlers.GetKeyHandler, "push", "pull")))
r.Methods("DELETE").Path("/v2/{imageName:.*}/_trust/tuf/").Handler(
prometheus.InstrumentHandlerWithOpts(
prometheusOpts("DeleteTuf"),
hand(handlers.DeleteHandler, "push", "pull")))
r.Methods("GET").Path("/_notary_server/health").HandlerFunc(health.StatusHandler)
r.Methods("GET").Path("/metrics").Handler(prometheus.Handler())
r.Methods("GET", "POST", "PUT", "HEAD", "DELETE").Path("/{other:.*}").Handler(
hand(handlers.NotFoundHandler))
return r
}
开发者ID:moxiegirl,项目名称:notary,代码行数:36,代码来源:server.go
示例19: startMonitoring
func startMonitoring(addr string) {
var redisActiveConn = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "redis_active_conn",
Help: "Number of active redis connections.",
})
prometheus.MustRegister(redisActiveConn)
var redisMaxConn = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "redis_max_conn",
Help: "Maximum number of redis connections.",
})
prometheus.MustRegister(redisMaxConn)
http.Handle("/metrics", prometheus.Handler())
redisMaxConn.Set(float64(redisPool.MaxActive))
go func() {
tick := time.NewTicker(1 * time.Second)
for range tick.C {
if redisPool == nil {
redisActiveConn.Set(0)
} else {
redisActiveConn.Set(float64(redisPool.ActiveCount()))
}
}
}()
err := http.ListenAndServe(addr, nil)
if err != nil {
lg.Fatal(err)
}
}
开发者ID:thomasf,项目名称:alkasir,代码行数:31,代码来源:central.go
示例20: testPrometheusCollector
func testPrometheusCollector(t *testing.T, c *PrometheusCollector, metricsFile string) {
rw := httptest.NewRecorder()
prometheus.Handler().ServeHTTP(rw, &http.Request{})
wantMetrics, err := ioutil.ReadFile(metricsFile)
if err != nil {
t.Fatalf("unable to read input test file %s", metricsFile)
}
wantLines := strings.Split(string(wantMetrics), "\n")
gotLines := strings.Split(string(rw.Body.String()), "\n")
// Until the Prometheus Go client library offers better testability
// (https://github.com/prometheus/client_golang/issues/58), we simply compare
// verbatim text-format metrics outputs, but ignore certain metric lines
// whose value depends on the current time or local circumstances.
for i, want := range wantLines {
if !includeRe.MatchString(want) || ignoreRe.MatchString(want) {
continue
}
if want != gotLines[i] {
t.Fatalf("unexpected metric line\nwant: %s\nhave: %s", want, gotLines[i])
}
}
}
开发者ID:zgfh,项目名称:cadvisor,代码行数:25,代码来源:prometheus_test.go
注:本文中的github.com/prometheus/client_golang/prometheus.Handler函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论