spring_opentelemetry/util/
http.rs

1use http::{Method, Request, Version};
2use http_body::Body;
3
4/// String representation of HTTP method
5pub fn http_method(method: &Method) -> &'static str {
6    match *method {
7        Method::GET => "GET",
8        Method::POST => "POST",
9        Method::PUT => "PUT",
10        Method::DELETE => "DELETE",
11        Method::HEAD => "HEAD",
12        Method::OPTIONS => "OPTIONS",
13        Method::CONNECT => "CONNECT",
14        Method::PATCH => "PATCH",
15        Method::TRACE => "TRACE",
16        _ => "_OTHER",
17    }
18}
19
20/// String representation of network protocol version
21pub fn http_version(version: Version) -> Option<&'static str> {
22    match version {
23        Version::HTTP_09 => Some("0.9"),
24        Version::HTTP_10 => Some("1.0"),
25        Version::HTTP_11 => Some("1.1"),
26        Version::HTTP_2 => Some("2"),
27        Version::HTTP_3 => Some("3"),
28        _ => None,
29    }
30}
31
32/// Get the size of the HTTP request body from the `Content-Length` header.
33pub fn http_request_size<B: Body>(req: &Request<B>) -> Option<u64> {
34    req.headers()
35        .get(http::header::CONTENT_LENGTH)
36        .and_then(|v| v.to_str().ok())
37        .and_then(|v| v.parse().ok())
38        .or_else(|| req.body().size_hint().exact())
39}
40
41/// Get the size of the HTTP response body from the `Content-Length` header.
42pub fn http_response_size<B: Body>(res: &http::Response<B>) -> Option<u64> {
43    res.headers()
44        .get(http::header::CONTENT_LENGTH)
45        .and_then(|v| v.to_str().ok())
46        .and_then(|v| v.parse().ok())
47        .or_else(|| res.body().size_hint().exact())
48}
49
50pub fn http_route<B>(req: &http::Request<B>) -> Option<&str> {
51    use axum::extract::MatchedPath;
52    req.extensions().get::<MatchedPath>().map(|matched_path| matched_path.as_str())
53}