rust - 如何在 Rocket.rs 的 url 中使用日期?

标签 rust rust-rocket rust-chrono

您如何更改 Rocket 网站上的示例以采用日期而不是年龄/u8

来自网站的示例:

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use] extern crate rocket;

#[get("/hello/<name>/<age>")]
fn hello(name: String, age: u8) -> String {
    format!("Hello, {} year old named {}!", age, name)
}

fn main() {
    rocket::ignite().mount("/", routes![hello]).launch();
}

我想要或多或少相同的输出(你好,58 岁,名叫约翰!),但有类似这样的输出

#[get("/hello/<name>/<birthdate>")]

而不是那个

#[get("/hello/<name>/<age>")]

我认为正确的结构是 chrono::DateTime不知何故rocket::request::FromParam参与其中,但我有点迷失了。

最佳答案

我们必须自己做这件事,这有点糟糕。

也许将来会提供一个库,让我们可以在 Rocket 和其他库之间进行互操作。

use chrono::NaiveDate;
use chrono::NaiveTime;
use chrono::NaiveDateTime;

// https://stackoverflow.com/questions/25413201/how-do-i-implement-a-trait-i-dont-own-for-a-type-i-dont-own
// https://github.com/SergioBenitez/Rocket/issues/602#issuecomment-380497269
pub struct NaiveDateForm(NaiveDate);
pub struct NaiveTimeForm(NaiveTime);
pub struct NaiveDateTimeForm(NaiveDateTime);

impl<'v> FromFormValue<'v> for NaiveDateForm {
    type Error = &'v RawStr;

    fn from_form_value(form_value: &'v RawStr) -> Result<NaiveDateForm, &'v RawStr> {
        let decoded = form_value.url_decode().map_err(|_| form_value)?;
        if let Ok(date) = NaiveDate::parse_from_str(&decoded, "%Y-%m-%d") {
            return Ok(NaiveDateForm(date));
        }
        Err(form_value)
    }
}

impl<'v> FromFormValue<'v> for NaiveTimeForm {
    type Error = &'v RawStr;

    fn from_form_value(form_value: &'v RawStr) -> Result<Self, Self::Error> {
        let decoded = form_value.url_decode().map_err(|_| form_value)?;
        if let Ok(time) = NaiveTime::parse_from_str(&decoded, "%H:%M:%S%.3f") {
            // if time.nanosecond() >= 1_000_000_000 {
            //     return Err(form_value);
            // }
            return Ok(NaiveTimeForm(time));
        }
        if let Ok(time) = NaiveTime::parse_from_str(&decoded, "%H:%M") {
            return Ok(NaiveTimeForm(time));
        }
        Err(form_value)
    }
}

impl<'v> FromFormValue<'v> for NaiveDateTimeForm {
    type Error = &'v RawStr;

    fn from_form_value(form_value: &'v RawStr) -> Result<NaiveDateTimeForm, &'v RawStr> {
        let decoded = form_value.url_decode().map_err(|_| form_value)?;
        if decoded.len() < "0000-00-00T00:00".len() {
            return Err(form_value)
        }
        let date = NaiveDateForm::from_form_value(RawStr::from_str(&decoded[.."0000-00-00".len()]))
            .map_err(|_| form_value)?;
        let time = NaiveTimeForm::from_form_value(RawStr::from_str(&decoded["0000-00-00T".len()..]))
            .map_err(|_| form_value)?;
        Ok(NaiveDateTimeForm(NaiveDateTime::new(*date, *time)))
    }
}

impl Deref for NaiveDateForm {
    type Target = NaiveDate;
    fn deref(&self) -> &NaiveDate {
        &self.0
    }
}

impl Deref for NaiveTimeForm {
    type Target = NaiveTime;
    fn deref(&self) -> &NaiveTime {
        &self.0
    }
}

impl Deref for NaiveDateTimeForm {
    type Target = NaiveDateTime;
    fn deref(&self) -> &NaiveDateTime {
        &self.0
    }
}

然后您应该能够执行以下操作:

#[get("/hello/<name>/<age>")]
fn hello(name: String, age: NaiveDateTimeForm) -> String {
    // Deref back to chrono::NaiveDatetime
    let date_time = *age;

    // write some code to figure out their age
}

我的依赖项:

chrono = { version = "0.4.19", features = ["serde"] }
rocket = "0.4.2"

这个实现大部分是从 https://github.com/chronotope/chrono/pull/362/files 窃取的。有人做了一个 PR 试图将这些东西放入 Chrono 中。

您可能应该有生日,而不是年龄,这样您就可以计算他们的年龄。

关于rust - 如何在 Rocket.rs 的 url 中使用日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55029850/

相关文章:

rust - Handlebars 三个阵列在一个循环中

rust - 代码中隐藏的逻辑错误?

rust - proc_macro_attribute似乎不能很好地与struct impls和traits一起使用

rust - 为什么我不能在线程之间发送 Mutex<*mut c_void>?

使用rust 柴油机 : the trait bound `NaiveDateTime: Deserialize<' _>` is not satisfied

postgresql - Rust:如何将SocketAddr转换为IpNetwork?

rust - 如何使用 rusqlite 在 sqlite 数据库中插入和获取日期?

unix - 在 Rust 中获取准确时间的正确方法?

rust - 如何将自定义 serde 解串器用于计时时间戳?

loops - 是否可以明确指定循环迭代的生命周期?