Skip to content

Commit

Permalink
add tide example
Browse files Browse the repository at this point in the history
  • Loading branch information
prabirshrestha committed Jun 6, 2020
1 parent 0d8ffc1 commit 8d2cb48
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 0 deletions.
14 changes: 14 additions & 0 deletions examples/tide/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "tide"
version = "0.4.0"
authors = ["Rasmus Kaj <[email protected]>"]
edition = "2018"

build = "src/build.rs"

[build-dependencies]
ructe = { path = "../..", features = ["mime03"] }

[dependencies]
async-std = { version = "1.6.0", features = ["attributes"] }
tide = "0.10.0"
9 changes: 9 additions & 0 deletions examples/tide/src/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//! This job builds rust source from templates,
//! which can then be `include!`d in `main.rs`.

use ructe::{Ructe, RucteError};

fn main() -> Result<(), RucteError> {
let mut ructe = Ructe::from_env()?;
ructe.compile_templates("templates")
}
24 changes: 24 additions & 0 deletions examples/tide/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// And finally, include the generated code for templates and static files.
include!(concat!(env!("OUT_DIR"), "/templates.rs"));

mod ructe_tide;
use ructe_tide::Render;

use tide::{Response, StatusCode};

#[async_std::main]
async fn main() -> Result<(), std::io::Error> {
let mut app = tide::new();

app.at("/").get(|_| async {
let mut res = Response::new(StatusCode::Ok);
res.render_html(|o| Ok(templates::hello(o, "world")?))?;
Ok(res)
});

let addr = "127.0.0.1:3000";
println!("Starting server on http://{}/", addr);
app.listen(addr).await?;

Ok(())
}
30 changes: 30 additions & 0 deletions examples/tide/src/ructe_tide.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
pub trait Render {
fn render<Call>(&mut self, call: Call) -> std::io::Result<()>
where
Call: FnOnce(&mut dyn std::io::Write) -> std::io::Result<()>;

fn render_html<Call>(&mut self, call: Call) -> std::io::Result<()>
where
Call: FnOnce(&mut dyn std::io::Write) -> std::io::Result<()>;
}

impl Render for tide::Response {
fn render<Call>(&mut self, call: Call) -> std::io::Result<()>
where
Call: FnOnce(&mut dyn std::io::Write) -> std::io::Result<()>,
{
let mut buf = Vec::new();
call(&mut buf)?;
self.set_body(buf);
Ok(())
}

fn render_html<Call>(&mut self, call: Call) -> std::io::Result<()>
where
Call: FnOnce(&mut dyn std::io::Write) -> std::io::Result<()>,
{
self.render(call)?;
self.set_content_type(tide::http::mime::HTML);
Ok(())
}
}
3 changes: 3 additions & 0 deletions examples/tide/templates/hello.rs.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
@(msg: &str)

hello @msg

0 comments on commit 8d2cb48

Please sign in to comment.