Skip to content

Commit

Permalink
examples/: Add actix-web binary (prometheus#76)
Browse files Browse the repository at this point in the history
Signed-off-by: ackintosh <sora.akatsuki@gmail.com>
  • Loading branch information
oriontvv authored and ackintosh committed Aug 27, 2022
1 parent 9e83678 commit cbd97ab
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Added a `with_prefix` method to `Registry` to allow initializing a registry with a prefix. See [PR 70].
- Added `Debug` implementations on most public types that were missing them. See [PR 71].
- Added example for actix-web framework. See [PR 76].

### Removed
- Remove `Add` trait implementation for a private type which lead to compile time conflicts with existing `Add` implementations e.g. on `String`. See [PR 69].
Expand All @@ -20,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
[PR 69]: https://github.com/prometheus/client_rust/pull/69
[PR 70]: https://github.com/prometheus/client_rust/pull/70
[PR 71]: https://github.com/prometheus/client_rust/pull/71
[PR 76]: https://github.com/prometheus/client_rust/pull/76

## [0.16.0]

Expand Down
1 change: 1 addition & 0 deletions Cargo.toml
Expand Up @@ -34,6 +34,7 @@ pyo3 = "0.16"
quickcheck = "1"
rand = "0.8.4"
tide = "0.16"
actix-web = "4"

[build-dependencies]
prost-build = { version = "0.9.0", optional = true }
Expand Down
74 changes: 74 additions & 0 deletions examples/actix-web.rs
@@ -0,0 +1,74 @@
use std::sync::Mutex;

use actix_web::{web, App, HttpResponse, HttpServer, Responder, Result};
use prometheus_client::encoding::text::{encode, Encode};
use prometheus_client::metrics::counter::Counter;
use prometheus_client::metrics::family::Family;
use prometheus_client::registry::Registry;

#[derive(Clone, Hash, PartialEq, Eq, Encode)]
pub enum Method {
Get,
Post,
}

#[derive(Clone, Hash, PartialEq, Eq, Encode)]
pub struct MethodLabels {
pub method: Method,
}

pub struct Metrics {
requests: Family<MethodLabels, Counter>,
}

impl Metrics {
pub fn inc_requests(&self, method: Method) {
self.requests.get_or_create(&MethodLabels { method }).inc();
}
}

pub struct AppState {
pub registry: Registry,
}

pub async fn metrics_handler(state: web::Data<Mutex<AppState>>) -> Result<HttpResponse> {
let state = state.lock().unwrap();
let mut buf = Vec::new();
encode(&mut buf, &state.registry)?;
let body = std::str::from_utf8(buf.as_slice()).unwrap().to_string();
Ok(HttpResponse::Ok()
.content_type("application/openmetrics-text; version=1.0.0; charset=utf-8")
.body(body))
}

pub async fn some_handler(metrics: web::Data<Metrics>) -> impl Responder {
metrics.inc_requests(Method::Get);
"okay".to_string()
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
let metrics = web::Data::new(Metrics {
requests: Family::default(),
});
let mut state = AppState {
registry: Registry::default(),
};
state.registry.register(
"requests",
"Count of requests",
Box::new(metrics.requests.clone()),
);
let state = web::Data::new(Mutex::new(state));

HttpServer::new(move || {
App::new()
.app_data(metrics.clone())
.app_data(state.clone())
.service(web::resource("/metrics").route(web::get().to(metrics_handler)))
.service(web::resource("/handler").route(web::get().to(some_handler)))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}

0 comments on commit cbd97ab

Please sign in to comment.