chiark / gitweb /
resource leaf routing: Attempt via impl FromRequest
authorIan Jackson <ijackson@chiark.greenend.org.uk>
Mon, 28 Mar 2022 00:40:58 +0000 (01:40 +0100)
committerIan Jackson <ijackson@chiark.greenend.org.uk>
Mon, 28 Mar 2022 00:50:52 +0000 (01:50 +0100)
I wrote this thinking that implementing FromRequest, so that we can
return Status::NOT_FOUND would work to pass on to the next route.
But, no.

Signed-off-by: Ian Jackson <ijackson@chiark.greenend.org.uk>
daemon/main.rs

index d19f0a289a39abe7af524c2e32df9851046dfde6..9e59add478b0d76e93d66ee83c66e561d63991e9 100644 (file)
@@ -129,6 +129,23 @@ struct CheckedResourceLeaf {
 #[error("not a valid resource path")]
 struct UnknownResource;
 
+impl ResponseError for UnknownResource {
+  fn status_code(&self) -> StatusCode { StatusCode::NOT_FOUND }
+  fn error_response(&self) -> HttpResponse<BoxBody> { error_response(self) }
+}  
+
+// Magically looks for "{leaf}"
+impl FromRequest for CheckedResourceLeaf {
+  type Error = UnknownResource;
+  type Future = future::Ready<Result<CheckedResourceLeaf, UnknownResource>>;
+  fn from_request(req: &HttpRequest, _: &mut actix_web::dev::Payload)
+                  -> Self::Future {
+    future::ready(
+      req.match_info().query("leaf").parse()
+    )
+  }
+}
+
 impl FromStr for CheckedResourceLeaf {
   type Err = UnknownResource;
   fn from_str(s: &str) -> Result<Self, Self::Err> {
@@ -298,8 +315,7 @@ async fn updates_route(query: Query<UpdatesParams>) -> impl Responder {
 
 #[route("/_/{leaf}", method="GET", method="HEAD")]
 #[throws(io::Error)]
-async fn resource(leaf: Path<Parse<CheckedResourceLeaf>>) -> impl Responder {
-  let leaf = leaf.into_inner().0;
+async fn resource(leaf: CheckedResourceLeaf) -> impl Responder {
   let path = match leaf.locn {
     RL::Main => format!("{}/{}", config().template_dir, leaf.safe_leaf),
     RL::Wasm(s) => format!("{}/{}", config().wasm_dir, s),