forked from plabayo/rama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_prometheus.rs
72 lines (68 loc) · 2.03 KB
/
http_prometheus.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//! An example to show how to expose your [`prometheus`]` metrics over HTTP
//! using the [`HttpServer`] and [`Executor`] from Rama.
//!
//! [`prometheus`]: https://crates.io/crates/prometheus
//! [`HttpServer`]: crate::http::server::HttpServer
//! [`Executor`]: crate::rt::Executor
//!
//! This example will create a server that listens on `127.0.0.1:8080.
//!
//! # Run the example
//!
//! ```sh
//! cargo run --example http_prometheus
//! ```
//!
//! # Expected output
//!
//! The server will start and listen on `:8080`. You can use `curl` to check if the server is ready:
//!
//! ```sh
//! curl -v http://127.0.0.1:8080
//! curl -v http://127.0.0.1:8080/metrics
//! ```
//!
//! With the seecoresponse you should see a response with `HTTP/1.1 200` and the `
use prometheus::{default_registry, Counter};
use rama::{
http::{
response::Html,
server::HttpServer,
service::web::{extract::State, prometheus_metrics, WebService},
},
rt::Executor,
};
#[derive(Debug)]
struct Metrics {
counter: Counter,
}
impl Default for Metrics {
fn default() -> Self {
let this = Self {
counter: Counter::new("example_counter", "example counter").unwrap(),
};
let registry = default_registry();
registry.register(Box::new(this.counter.clone())).unwrap();
this
}
}
#[tokio::main]
async fn main() {
let exec = Executor::default();
HttpServer::auto(exec)
.listen_with_state(
Metrics::default(),
"127.0.0.1:8080",
// by default the k8s health service is always ready and alive,
// optionally you can define your own conditional closures to define
// more accurate health checks
WebService::default()
.get("/", |State(metrics): State<Metrics>| async move {
metrics.counter.inc();
Html(format!("<h1>Hello, #{}!", metrics.counter.get()))
})
.get("/metrics", prometheus_metrics),
)
.await
.unwrap();
}