4
3

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をやっていきたい

Last updated at Posted at 2018-09-03

c++の代替みたいな感じですかね。速いことで有名。single coreを余すことなく使うらしい。

基本的には、cargoでinstallしたりbuildしたり。cargo.tomlを作ります。rocketというフレームワークが便利そう。dbとの接続はdieselを使う感じ。

とりあえず、rocketから触ってみることに。

api server立てるっぽいやつを動かしてみる。ここでコードの内容も見ていく。

$ rustc -V
$ cargo -V

$ git clone https://github.com/SergioBenitez/Rocket
$ cd Rocket/example/json
$ rustup override set nightly

$ cat Cargo.toml
$ cargo build
$ cargo run

$ cat src/main.rs

# check
$ curl localhost:8000/message/1
# post
$ curl -H 'Content-Type:application/json' -d '{ "contents": "Hello, world!" }' localhost:8000/message/1
# get
$ curl localhost:8000/message/1

次は、dbを組み合わせた感じのものを見ていきます。

$ heroku create $APP_NAME
$ heroku addons:create heroku-postgresql:hobby-dev -a $APP_NAME
$ heroku config -a $APP_NAME

$ git clone https://github.com/ghotiphud/rust-web-starter
$ cd !$:t
$ docker-compose up

$ curl localhost:3000/api
or
$ wrk -t12 -c400 -d30s http://localhost:3000/api

この場合は、./webがfrontendで./api_serverがbackendになります。つまり、./api_serverがrustで書かれています。herokuなどにdeployする場合は、Procfileに以下のように記述すればいいでしょう。frontendはnpmするだけのものが多いので、特にありません。react使ってる人が多い印象。

$ cargo build --release
$ echo "ROCKET_ENV=prod target/release/api_server" >> Procfile

重要なのはreadmeにも書いてますけど、dieselになります。大抵、repoに./migrationsが用意されてますので、diesel migration runすればpreviewはできます。

$ cargo install diesel_cli
$ echo "DATABASE_URL=postgres://user:pass@localhost/name" > .env
$ diesel migration generate name
$ diesel migration run

コードの内容については、こちらが参考になりそうな感じだった。

感想

rustは、依存パッケージでハマると、ものすごく時間を浪費してしまう感じで、その点はつらいですね。

その分、api serverとかをrustで選択するのは、やりやすそうな感じでした。書けると選択肢広がりそうな言語です。

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?