Rustでwebアプリを実装して勉強 その5 - テンプレートを使ってhtmlを返す

Rust初心者が勉強したことを記録する備忘録。

今日やった事

今日はRustやる時間が少ないので、handlebarsを使ってhtmlを返すところを少しだけ試した。

github.com

handlebars の使い方

actix-webのexamplesを参考にして、そのままコピペした。

// Handlebars uses a repository for the compiled templates. This object must be
// shared between the application threads, and is therefore passed to the
// Application Builder as an atomic reference-counted pointer.

サンプルコードのコメントに書いてあるように、Handlebars のインスタンスは各スレッドで共有するために web::Data を使う。

html を検証する

html を assert_eq! で検証するのは大変なので、部分一致で確認するように修正した。

- assert_eq!(test::read_body(resp), Bytes::from_static(b"Hello world!"));
+ let html = str::from_utf8(&test::read_body(resp))
+    .expect("Could not convert response to UTF8")
+     .to_string();
+ assert!(html.contains("<h1>Hello world!</h1>"));

& をつけたり、str や String の関係がよく分かってないが、とりあえずこんな感じで書くことで部分一致を検証できた。

次にやりたいこと

試したいことはだいたいできたので、次はコードを整理したい。

  • SQLに関する処理をModelに移す(もしくはRepositoryを作る)
  • テストコードを書く
  • jsonを返すように直す
  • テンプレートエンジンを使ってhtmlを返す
  • テスト環境の改善(コードのリファクタリングトランザクション周りの設定など)
  • Dockerで動くように直す
  • Herokuで動かす