• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Rust Rocket web 框架学习 二Request

武飞扬头像
乐虚
帮助1

Rocket Request

GET

  1. 添加 get 过程宏,并使用 <xxx>, 指定请求参数

    #[get("/hello/<name>/<age>/<cool>")]
    fn hello(name: &str, age: u8, cool: bool) -> String {
       if cool {
          format!("You're a cool {} year old, {}!", age, name)
       } else {
          format!("{}, we need to talk about your coolness.", name)
       }
    }
    
    
  2. 通过 <xxx...>指定 list 参数

    use std::path::PathBuf;
    
    #[get("/page/<path..>")]
    fn get_page(path: PathBuf) { /* ... */ }
    
  3. 通过 routes! ,注册路由

       rocket::build()
          .mount("/", routes![index])
          .mount("/base", routes![get_exs, get_ex, post_ex, put_ex, delete_ex])
    

POST

  1. 添加 post 过程宏,并使用 data = <xxx>, 指定 body dataxxx 必须实现 FromData trait

    # [post("/", data = "<input>")]
    fn new(input: T) { /* .. */ }
    
  2. 也可以使用 JSON 作为 body data

    use rocket::serde::{Deserialize, json::Json};
    
    #[derive(Deserialize)]
    #[serde(crate = "rocket::serde")]
    struct Task<'r> {
       description: &'r str,
       complete: bool
    }
    
    #[post("/todo", data = "<task>")]
    fn new(task: Json<Task<'_>>) { /* .. */ }
    

JSON

  1. Cargo.toml 中添加 json feature.

    rocket = { version = "=0.5.0-rc.3", features = ["json"] }
    
  2. 引入 Rocket 中的 json crate

    use rocket::serde::json::serde_json::json;
    use rocket::serde::json::{Json, Value};
    use rocket::serde::{Deserialize, Serialize};
    
  3. 创建结构体,并序列化

    #[derive(Serialize, Deserialize)]
    #[serde(crate = "rocket::serde")]
    struct Person<'a> {
       id: usize,
       name: &'a str,
       age: u8,
    }
    
    
  4. 通过 Json 结构体 或 json!, 创建 Json

    #[get("/")]
    fn index<'a>() -> Json<Person<'a>> {
       Json(Person {
          id: 0,
          name: "Tome",
          age: 9,
       })
    }
    
    #[get("/ex/<id>")]
    async fn get_ex(id: usize) -> Value {
       json!(Person { id, name: "Joy", age: 10 })
    }
    
  5. 完整代码参考: github.com/panmin-code…

参考

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgeejke
系列文章
更多 icon
同类精品
更多 icon
继续加载