https://rocket.rs/v0.4/guide/requests/ ## Dynamic Pathsの指定 `<...>`の形で指定し、関数の引数に[[RawStr]]の参照型で追加。 ```rust #[get("/hello/<word>")] fn index(word: &RawStr) -> String { format!("Hello, world! {}", word) } ``` [rocket::request::FromParam]トレイトが実装されていれば、他の型も使える。一覧は[rocket::request::FromParam]の`Implementations on Foreign Types`で確認できる。 [rocket::request::FromParam]: https://api.rocket.rs/master/rocket/request/trait.FromParam.html ## Queryの指定 ### Structを使わない Pathと同じ要領でOK。 ```rust #[get("/hello?<prefix>&<suffix>")] fn index(prefix: String, suffix: String) -> String { format!("{}, Hello, world! {}", prefix, suffix) } ``` ```bash $ curl "http://localhost:8000/hello?prefix=AAA&suffix=ZZZ" AAA, Hello, world! ZZZ ``` 関数の引数を[[Option (Rust)|Option]]にすればOptionalになる。 ```rust #[get("/hello?<prefix>&<suffix>")] fn index(prefix: String, suffix: Option<String>) -> String { format!( "{}, Hello, world! {}", prefix, suffix.unwrap_or_else(|| "".into()) ) } ``` ```bash $ curl "http://localhost:8000/hello?prefix=AAA" AAA, Hello, world! $ curl "http://localhost:8000/hello?prefix=AAA&suffix=ZZZ" AAA, Hello, world! ZZZ ``` ### Structを使う `FromForm`トレイトを実装し、`<form..>`とquery guardの表現を使う。 ```rust #[derive(FromForm)] struct HelloForm { prefix: String, suffix: Option<String>, } #[get("/hello?<form..>")] fn index(form: Form<HelloForm>) -> String { format!( "{}, Hello, world! {}", form.prefix, form.suffix.clone().unwrap_or_else(|| "".into()) ) } ``` Optionalについては同じ。