在先前的文章中,有介紹過用 Rust 程式語言搭配 MongoDB 來儲存檔案的方式,那麼要如何將其應用到 Rocket 框架中,使 Rocket 框架能夠回應檔案中心儲存的資料呢?
File Center Raw Response on MongoDB for Rocket Framework
「File Center Raw Response on MongoDB for Rocket Framework」是筆者開發的套件,可以讓「Mongo File Center」套件融入 Rocket 框架中,能直接從檔案中心回應檔案資料,並且支援 HTTP 的 ETag 機制。
Crates.io
Cargo.toml
使用方法
先將 mongo_file_center 這個 crate 下的 FileCenter 結構實體註冊至 Rocket 框架的應用程式狀態中。在路由處理程序中,可以利用 State<FileCenter> 的 inner 方法取得 FileCenter 結構實體的參考。
rocket_mongo_file_center_raw_response 這個 crate 提供了 FileCenterRawResponse 結構體和 EtagIfNoneMatch 結構體(來自 rocket_etag_if_none_match 這個 crate,請參考這篇文章來了解 EtagIfNoneMatch 結構體)。
FileCenterRawResponse 結構體有三個關聯函數可以用來產生 FileCenterRawResponse 結構體的實體。
首先介紹最常用的 from_id_token 函數。呼叫 from_id_token 函數時,要從參數傳入 FileCenter 結構實體的參考、EtagIfNoneMatch 結構實體的參考、檔案中心加密過的 Object ID(ID token) 和檔案名稱(如果不設定則使用檔案中心儲存的檔案名稱)。
以下是一個完整的例子:
#[macro_use]
extern crate rocket;
use std::error::Error;
use std::path::Path;
use rocket_mongo_file_center_raw_response::mongo_file_center::{mime, FileCenter};
use rocket_mongo_file_center_raw_response::{EtagIfNoneMatch, FileCenterRawResponse};
use rocket::http::Status;
use rocket::State;
const URL: &str = "mongodb://localhost:27017";
#[get("/<id_token>")]
async fn view(
etag_if_none_match: &EtagIfNoneMatch<'_>,
file_center: &State<FileCenter>,
id_token: String,
) -> Result<Option<FileCenterRawResponse>, Status> {
FileCenterRawResponse::from_id_token(
file_center.inner(),
etag_if_none_match,
id_token,
None::<String>,
)
.await
.map_err(|_| Status::InternalServerError)
}
#[rocket::main]
async fn main() -> Result<(), Box<dyn Error>> {
let file_center = FileCenter::new(URL).await?;
let path = Path::new("examples").join("images").join("image(貓).jpg");
let file_id =
file_center.put_file_by_path(path, None::<String>, Some(mime::IMAGE_JPEG)).await?;
let id_token = file_center.encrypt_id(file_id);
println!("The ID token is: {}", id_token);
println!();
rocket::build().manage(file_center).mount("/", routes![view]).launch().await?;
Ok(())
}
程式一開始,會將工作目錄下的 examples/images/image(貓).jpg 這張 JPEG 圖檔儲存到檔案中心中,然後在螢幕上顯示出這筆加密過的 Object ID(也就是「ID token」)。接著將檔案中心註冊給 Rocket,並啟動 Rocket。在 view 這個路由處理程序中,會讀取網址路徑中帶的 ID token。from_id_token 會根據這個 ID token 來查詢檔案中心裡對應的檔案,並回傳 Result<Option<FileCenterRawResponse>, FileCenterError>,注意因為這邊的 FileCenterError 並沒有實作 rocket::response::Responder 特性,所以不能直接拿來回傳,要像範例程式這樣先用 map_err 方法轉成 Status 等有實作 Responder 特性的型別。
使用 from_id_token 關聯函數來建立 FileCenterRawResponse 結構實體會強制使用 ETag 機制,ETag 值即為 ID token。如果是用 from_object_id 關聯函數來建立 FileCenterRawResponse 結構實體,若要使用 ETag 機制,就要自行去計算 ETag 值並透過參數傳給 from_object_id 關聯函數來使用。例如把以上的 view 路由處理程序用 from_object_id 關聯函數改寫的話就會變成以下這樣:
#[get("/<id_token>")]
async fn view(
etag_if_none_match: &EtagIfNoneMatch<'_>,
file_center: &State<FileCenter>,
id_token: String,
) -> Result<Option<FileCenterRawResponse>, Status> {
let object_id =
file_center.decrypt_id_token(&id_token).map_err(|_| Status::InternalServerError)?;
let etag = FileCenterRawResponse::create_etag_by_id_token(id_token);
FileCenterRawResponse::from_object_id(
file_center.inner(),
Some(etag_if_none_match),
Some(etag),
object_id,
None::<String>,
)
.await
.map_err(|_| Status::InternalServerError)
}
以上程式中,FileCenterRawResponse 結構體的 create_etag_by_id_token 關聯函數可以拿來將 ID token 轉成 rocket_etag_if_none_match::entity_tag::EntityTag 結構實體。
如果已經從檔案中心拿到 FileItem 了,可以使用 FileCenterRawResponse 結構體的 from_file_item 關聯函數來產生 FileCenterRawResponse 結構實體,如下:
#[get("/<id_token>")]
async fn view(
etag_if_none_match: &EtagIfNoneMatch<'_>,
file_center: &State<FileCenter>,
id_token: String,
) -> Result<Option<FileCenterRawResponse>, Status> {
let object_id =
file_center.decrypt_id_token(&id_token).map_err(|_| Status::InternalServerError)?;
let etag = FileCenterRawResponse::create_etag_by_id_token(id_token);
if etag_if_none_match.weak_eq(&etag) {
Err(Status::NotModified)
} else {
let file_item = file_center
.get_file_item_by_id(object_id)
.await
.map_err(|_| Status::InternalServerError)?;
match file_item {
Some(file_item) => {
Ok(Some(FileCenterRawResponse::from_file_item(
Some(etag),
file_item,
None::<String>,
)))
}
None => Ok(None),
}
}
}
from_file_item 關聯函數不能幫忙判斷 HTTP 請求中的 If-None-Match 欄位,因為這個動作需在呼叫 from_file_item 關聯函數之前就完成才比較有意義(如果判斷結果是 304,就不需要再浪費時間查詢資料庫)。因此以上程式是在路由處理程序中另外撰寫程式碼來判斷 ETag。
