8
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rust のウェブフレームワーク「Rocket」とたわむれてみた。

Posted at

諸注意

  • Rust超初心者です。お手柔らかにお願いします。
  • いつもはpythonとC++を使うことが多いですが、Rust書いてみたかったので触ってみました。
  • これを書く前に同じくRustのウェブフレームワークの「Iron」を触ってみましたが(この記事=>test)、なかなか難しいなという印象でしたので、一種の希望を持って「Rocket」も触ってみました。

やったこと

  • キータに上がっていたすばらしい記事(RustのRocketでWebアプリケーションを作ってみる)を追いかけてみました。
    • レコード(ストラクト)をjsonとして返す。
    • jsonをpostで受け取る。
    • getリクエストからidを受け取り、それに対応したレコードを返す。
    • 202をつけてレコードを返却する。

rustの環境

$ rustc --version
rustc 1.40.0-nightly (1423bec54 2019-11-05)

感想

  • RocketのドキュメンテーションはIronに比べてとてもわかりやすい、すばらしい!(Rocketドキュメントはこちら)

やっぱり新しい言語勉強する時に、チュートリアルが動かないと辛いですよね、、
下のコードは下の環境下で動くことを確認済みなので、ぜひ使ってみてください!

これからRustを勉強して更新してけたらと思います!
「いいね」や「コメント」お待ちしております!!

Rocket

いつものごとくプロジェクトを作ります。

cargo new web_rocket
$tree src
src
├── main.rs
├── models.rs
└── routes.rs

Cargo.toml

[dependencies]
rocket = "0.4"
rocket_contrib = { version = "0.4", features = ["json"] }
# serdeのcrateを追加する
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.0"

main.rs

# ![feature(proc_macro_hygiene)]
# ![feature(decl_macro)]

# [macro_use]
extern crate rocket;

mod models;
mod routes;

// WebAPIのURLルーティングはroutes.rsに移動する
use routes::*;

// rocketにルーティングをマウントして、開始する。
fn main() {
    rocket::ignite()
        .mount("/", routes![index, todos, new_todo, todo_by_id,todos_accepted])
        .launch();
}

routes.rs

// JSONを返すのに必要
use rocket_contrib::json::Json;

//models.rsからToDo(テーブルに相当するストラクト)をインポートする。
use crate::models::ToDo;


// hello world を返却する
// flaskと似た感じで書ける。
# [get("/")]
pub fn index() -> &'static str {
    "Hello, world!"
}

/// TODOリストを返す。
/// Jsonの型がResponderをimplしているので、JSON文字列を返すことができる
# [get("/todos")]
pub fn todos() -> Json<Vec<ToDo>> {
    Json(vec![ToDo {
        id: 1,
        title: "Read Rocket tutorial".into(),
        description: "Read https://rocket.rs/guide/quickstart/".into(),
        done: false,
    }])
}

/// 新しいTODOを作成する
/// POSTの時はこうする
# [post("/todos", data = "<todo>")]
pub fn new_todo(todo: Json<ToDo>) -> String {
    format!("Accepted post request! {:?}", todo.0)
}

/// TODOをidを指定して取得する
# [get("/todos/<todoid>")]
pub fn todo_by_id(todoid: u32) -> String {
    let todo = ToDo {
        id: 1,
        title: "Read Rocket tutorial".into(),
        description: "Read https://rocket.rs/guide/quickstart/".into(),
        done: false,
    };
    format!("{:?}", todo)
}

//Acceptedで202を付加してTODOを返却する。
use rocket::response::status::Accepted;
# [get("/todos_accepted")]
pub fn todos_accepted() -> Accepted<Json<Vec<ToDo>>> {
    Accepted(Some(Json(vec![ToDo {
        id: 1,
        title: "Read Rocket tutorial".into(),
        description: "Read https://rocket.rs/guide/quickstart/".into(),
        done: false,
    }])))
}

models.rs

use serde::{Deserialize, Serialize};

/// TODOのモデルはmodels.rsに定義
# [derive(Debug, Serialize, Deserialize)]
pub struct ToDo {
    pub id: u32,
    pub title: String,
    pub description: String,
    pub done: bool,
}
8
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?