Rust heroku Hello Worldまで
環境です。
$ cat /etc/lsb-release DISTRIB_ID=Ubuntu DISTRIB_RELEASE=20.04 DISTRIB_CODENAME=focal DISTRIB_DESCRIPTION="Ubuntu 20.04.2 LTS" $ cargo --version cargo 1.50.0 (f04e7fab7 2021-02-04) $ heroku --version heroku/7.48.0 linux-x64 node-v12.16.2
herokuの登録、loginはできているものとします。
cargo new sample cd sample git init heroku create app-name --buildpack emk/rust echo 'web: /target/release/sample' > Procfile echo '/target' >> .gitignore echo '**/*.rs.bk' >> .gitignore
sampleやapp-nameのところは適宜変更する。
必要なクレートを追加する。
cargo add actix_web cargo add env_logger
main.rsは以下
use actix_web::{get, App, HttpResponse, HttpServer}; use std::env; #[actix_web::main] async fn main() -> Result<(), actix_web::Error> { std::env::set_var("RUST_LOG", "actix_web=info"); env_logger::init(); let port = env::var("PORT") .unwrap_or_else(|_| "3000".to_string()) .parse() .expect("PORT must be a number"); HttpServer::new(move || App::new().service(index)) .bind("0.0.0.0:8080")? .bind(("0.0.0.0", port))? .run() .await?; Ok(()) } #[get("/")] async fn index() -> Result<HttpResponse, actix_web::Error> { let response_body = "Hello World!\n"; Ok(HttpResponse::Ok().body(response_body)) }
デプロイして、終了!
git add . git commit -m "comment" git push heroku master
heroku open
で確認できる。