Rust Rocket web 框架学习 一 Hello world

506 阅读1分钟

Rocket

初始化

  1. 使用 Rust 最新特性: rustup default stable

  2. 创建 Rust 项目:

    cargo new hello-rocket --bin
    cd hello-rocket
    
  3. Cargo.toml 中添加 rocket依赖

    rocket = { version = "=0.5.0-rc.3", features = ["json"] }
    
  4. main.rs 中添加下面的代码

    use rocket::{get, launch, routes};
    
    #[get("/")]
    fn index() -> &'static str {
        "Hello world!"
    }
    
    #[launch]
    fn rocket() -> _ {
        rocket::build().mount("/", routes![index])
    }
    
    // 或者
     #[rocket::main]
     async fn main() -> Result<(), Box<dyn std::error::Error>> {
         rocket::build().mount("/", routes![index]).launch().await?;
    
         Ok(())
     }
    
    
  5. 执行 cargo run

  6. 浏览器访问: http://127.0.0.1:8000/, 可以看到 Hello world!

参考