環境
- winodws 10
- wsl2
Rustのインストール
wsl2上のRustの開発環境をセットアップしておく。
$ curl https://sh.rustup.rs -sSf | sh
入力を求められるので
> 1
$ echo 'export PATH="$HOME/.cargo/bin:$PATH"' >> ~/.bashrc
$ source ~/.bashrc
インストールできたか確認
適当なディレクトリで
$ cargo new hello
$ cd hello
$ cargo build
$ cargo run
> Hello, world!
実行時このようなエラーが出た場合
note: No such file or directory (os error 2)
buildに必要なものが足りていないので、build-essentialをインストールする。
$ sudo apt update
$ sudo apt install build-essential
REST APIの実装
公式のチュートリアルを見て実装するもエラー吐いてbuildできなかったので(JSONのパースでこける)ので、ゴリゴリ書く。
Cargo.toml
[package]
name = "hello"
version = "0.1.0"
authors = ["ubuntu"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rustc-serialize = "0.3"
reqwest = "0.9"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
[dependencies.nickel]
version = "*"
# If you are using the 'nightly' rust channel you can uncomment
# the line below to activate unstable features
# features = ["unstable"]
# Some examples require the `rustc_serialize` crate, which will
# require uncommenting the lines below
# [dependencies]
# rustc-serialize = "*"
[dev-dependencies]
serde_derive = "1.0"
rust
#[macro_use] extern crate nickel;
extern crate rustc_serialize;
use std::collections::BTreeMap;
use nickel::status::StatusCode;
use nickel::{Nickel, JsonBody, HttpRouter, MediaType};
use rustc_serialize::json::{Json, ToJson};
use serde::{Serialize, Deserialize};
#[derive(Debug, Serialize, Deserialize)]
struct Person {
firstname: String,
lastname: String,
}
impl ToJson for Person {
fn to_json(&self) -> Json {
let mut map = BTreeMap::new();
map.insert("firstname".to_string(), self.firstname.to_json());
map.insert("lastname".to_string(), self.lastname.to_json());
Json::Object(map)
}
}
fn main() {
let mut server = Nickel::new();
server.post("/", middleware! { |request, response|
let person = try_with!(response, {
request.json_as::<Person>().map_err(|e| (StatusCode::BadRequest, e))
});
format!("Hello {} {}", person.firstname, person.lastname)
});
server.get("/raw", middleware! { |_, mut response|
response.set(MediaType::Json);
r#"{ "foo": "bar" }"#
});
server.listen("127.0.0.1:6767").unwrap();
}
これだけ書いておけば大体の人は使えるやろ(適当)