Basic run with tera templating
Signed-off-by: baalajimaestro <me@baalajimaestro.me>
This commit is contained in:
parent
0bdf93d737
commit
db32d8b07e
3 changed files with 40 additions and 14 deletions
38
src/main.rs
38
src/main.rs
|
@ -1,26 +1,36 @@
|
|||
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};
|
||||
use actix_web::{get, App, HttpResponse, HttpServer, Responder, web::{Data}};
|
||||
use tera::{Tera, Context};
|
||||
|
||||
#[get("/")]
|
||||
async fn hello() -> impl Responder {
|
||||
HttpResponse::Ok().body("Hello world!")
|
||||
struct Template {
|
||||
paste: Tera,
|
||||
}
|
||||
|
||||
#[post("/echo")]
|
||||
async fn echo(req_body: String) -> impl Responder {
|
||||
HttpResponse::Ok().body(req_body)
|
||||
}
|
||||
|
||||
async fn manual_hello() -> impl Responder {
|
||||
HttpResponse::Ok().body("Hey there!")
|
||||
#[get("/{paste_id}")]
|
||||
async fn paste_render(data: Data<Template>) -> impl Responder {
|
||||
let my_data = data.get_ref();
|
||||
let mut context = Context::new();
|
||||
context.insert("paste_id", "owo");
|
||||
let rendered = my_data.paste.render("paste.html", &context);
|
||||
HttpResponse::Ok().body(rendered.unwrap())
|
||||
}
|
||||
|
||||
#[actix_web::main]
|
||||
|
||||
async fn main() -> std::io::Result<()> {
|
||||
HttpServer::new(|| {
|
||||
|
||||
let tera = match Tera::new("templates/*.html") {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
println!("Parsing error(s): {}", e);
|
||||
::std::process::exit(1);
|
||||
}
|
||||
};
|
||||
let data = Data::new(Template { paste: tera });
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.service(hello)
|
||||
.service(echo)
|
||||
.route("/hey", web::get().to(manual_hello))
|
||||
.app_data(Data::clone(&data))
|
||||
.service(paste_render)
|
||||
})
|
||||
.bind(("127.0.0.1", 8080))?
|
||||
.run()
|
||||
|
|
11
templates/base.html
Normal file
11
templates/base.html
Normal file
|
@ -0,0 +1,11 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Actix Web</title>
|
||||
</head>
|
||||
<body>
|
||||
{% block content %}
|
||||
{% endblock content %}
|
||||
</body>
|
||||
</html>
|
5
templates/paste.html
Normal file
5
templates/paste.html
Normal file
|
@ -0,0 +1,5 @@
|
|||
{% extends "base.html" %}
|
||||
|
||||
{% block content %}
|
||||
<h1>This is {{paste_id}}</h1>
|
||||
{% endblock content %}
|
Loading…
Reference in a new issue