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