Repository navigation
Expand file tree
/
Copy pathtide.rs
More file actions
86 lines (73 loc) · 2.34 KB
/
Copy pathtide.rs
File metadata and controls
86 lines (73 loc) · 2.34 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use prometheus_client::encoding::EncodeLabelValue;
use prometheus_client::encoding::{text::encode, EncodeLabelSet};
use prometheus_client::metrics::counter::Counter;
use prometheus_client::metrics::family::Family;
use prometheus_client::registry::Registry;
use std::sync::Arc;
use tide::{Middleware, Next, Request, Result};
#[async_std::main]
async fn main() -> std::result::Result<(), std::io::Error> {
tide::log::start();
let mut registry = Registry::default();
let http_requests_total = Family::<Labels, Counter>::default();
registry.register(
"http_requests_total",
"Number of HTTP requests",
http_requests_total.clone(),
);
let middleware = MetricsMiddleware {
http_requests_total,
};
let mut app = tide::with_state(State {
registry: Arc::new(registry),
});
app.with(middleware);
app.at("/").get(|_| async { Ok("Hello, world!") });
app.at("/metrics")
.get(|req: tide::Request<State>| async move {
let mut encoded = String::new();
encode(&mut encoded, &req.state().registry).unwrap();
let response = tide::Response::builder(200)
.body(encoded)
.content_type("application/openmetrics-text; version=1.0.0; charset=utf-8")
.build();
Ok(response)
});
app.listen("127.0.0.1:8080").await?;
Ok(())
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, EncodeLabelSet)]
struct Labels {
method: Method,
path: String,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, EncodeLabelValue)]
enum Method {
Get,
Put,
}
#[derive(Clone)]
struct State {
registry: Arc<Registry>,
}
#[derive(Default)]
struct MetricsMiddleware {
http_requests_total: Family<Labels, Counter>,
}
#[tide::utils::async_trait]
impl Middleware<State> for MetricsMiddleware {
async fn handle(&self, req: Request<State>, next: Next<'_, State>) -> Result {
let method = match req.method() {
http_types::Method::Get => Method::Get,
http_types::Method::Put => Method::Put,
_ => todo!(),
};
let path = req.url().path().to_string();
let _count = self
.http_requests_total
.get_or_create(&Labels { method, path })
.inc();
let res = next.run(req).await;
Ok(res)
}
}