salvo-rs / salvo

A powerful web framework built with a simplified design.
https://salvo.rs
Apache License 2.0
2.92k stars 172 forks source link

Get matched route information #822

Open cortopy opened 1 week ago

cortopy commented 1 week ago

Is your feature request related to a problem? Please describe.

When a Request is processed, I need to log which route is being handled. The Opentelemetry definition of route is very handy:

The matched route, that is, the path template in the format used by the respective server framework.

And they give examples like: /users/:userID?, {controller}/{action}/{id?}

I need this because:

Describe the solution you'd like It'd be amazing if Request or Response had something like:


struct RouteInformation {
   path: &str
}

impl RouteInformation {
  pub fn masked_uri() -> String {
     // Some logic to replace parameters with something lkike ****
  }
}

struct Request {
   route: RouteInformation,
   ...
}
#[async_trait]
impl Handler for Logger {
    async fn handle(
        &self,
        req: &mut Request,
        depot: &mut Depot,
        res: &mut Response,
        ctrl: &mut FlowCtrl,
    ) {
        let span = info_span!(
            "Request",
            // Instead of: path = %req.uri(),
            url.path = %req.route.masked(),
            http.route = %req.route.path(),
        );

        async move {
            let now = Instant::now();
            ctrl.call_next(req, depot, res).await;
            let duration = now.elapsed();

            let status = res.status_code.unwrap_or(match &res.body {
                ResBody::None => StatusCode::NOT_FOUND,
                ResBody::Error(e) => e.code,
                _ => StatusCode::OK,
            });
            info!(
                http.response.status_code = %status,
                http.duration = ?duration,
                "Response"
            );
        }
        .instrument(span)
        .await
    }
}

Describe alternatives you've considered Request doesn't provide information about routes so it would be some laborious manual process for each known route. This would be prone to error.