A toy web framework inspired by gin-gonic/gin and expressjs/express.
Just add rum_framework to the dependencies of Cargo.toml
.
[dependencies]
rum_framework = "0.0.1"
HTML rendering and json serilization relies on Keats/tera and serde-rs/serde. If you need these features, please also install them on your projects.
use rum_framework::rum;
let mut rum_server = rum::new("127.0.0.1", 3000);
The controller can be implemented by using the function or closure that has argument with &mut RumContext
type.
When a response is returned from middleware, following middlewares and controllers will not be executed.
fn verify(c: &mut RumContext){
//do stuff
...
c.file(201, "test.jpg"); // return response with status code and contents.
}
The response can be generated by following methods of context:
file
read file and return binary data.text
return plain text.html
render html and return html response.json
return json data.
You can also use RumContext
to communicate with following controllers, or getting parameters from requests. (e.g. get_request_body
)
rum_server.post("/test/a1/:param1/b/:param2/c", |c:&mut RumContext|{
let point = Point { x: 1, y: 2 };
c.json(200, serde_json::to_string(&point).unwrap());
});
rum_server.global_middleware(vec![session, verify]);
rum_server.middleware("/test",vec![is_admin]);
use rum_framework::rum;
use rum_framework::context::RumContext;
use serde::{Serialize, Deserialize};
use tera::Context;
#[derive(Serialize, Deserialize, Debug)]
struct Point {
x: i32,
y: i32,
}
#[derive(Serialize, Deserialize, Debug)]
struct Test {
test: String,
}
fn session(_: &mut RumContext){
println!("called first.");
}
fn verify(c: &mut RumContext){
println!("called second.");
let ua = c.get_request_header("User-Agent");
if ua.is_none(){
// Abort Operation if header is invalid.
c.text(400, "bad request");
}
}
fn is_admin(_: &mut RumContext){
println!("verifying permission.");
}
fn index(c: &mut RumContext){
println!("index executed!");
c.set_response_header("Access-Control-Allow-Origin", "http://127.0.0.1:8000");
c.file(201, "test.jpg");
}
fn main() {
let mut rum_server = rum::new("127.0.0.1", 3000);
rum_server.use_html_template("templates/*.html");
rum_server.use_static_assets("static");
rum_server.global_middleware(vec![session, verify]);
rum_server.get("", index);
rum_server.post("/test/a1/:param1/b/:param2/c", |c:&mut RumContext|{
let point = Point { x: 1, y: 2 };
c.json(200, serde_json::to_string(&point).unwrap());
});
rum_server.get("/test/b1", |c: &mut RumContext|{
let mut context = Context::new();
context.insert("val1", &"Hello!");
context.insert("val2", &2023);
c.html(200, "index.html", &context);
});
rum_server.middleware("/test",vec![is_admin]);
rum_server.start();
}