#web #macro #pack #post #web-programming #body #parse

amper

Pack of macros for web-programming in Rust

2 releases (1 stable)

1.0.0 Sep 26, 2021
0.1.0 Sep 25, 2021

#999 in HTTP server

MIT license

7KB
96 lines

Amper

Pack of macros for web-programming in Rust

A simple package with attributes to bind function patterns to the framework actix-web.

#[GET("/")]
fn index() {
    "nice"
}

turn into

#[get("/")]
async fn index() -> impl Responder {
    "nice"
}

There are 3 attributes in total

#[GET("/"]
#[POST("/")]
#[SERVER]

POST need set to POST request (There is also a special type for handling structs as post requests, which is actix_web::web::Form;)

#[derive(Debug)]
#[derive(Deserialize)]  // (yea, use serde)
struct User {
    username: String,
    email: String,
    password: String
}

#[POST("/")]
fn index_analyz(data: Post<User>) {
    println!("{:#?}", data);
    "nice"
}

SERVER set to main of your site

#[SERVER]
fn main() {
    HttpServer::new(|| {
        App::new()
            .service(index)
            .service(index_analyz)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

And a little with macros setting HttpResponce for the kind of response body.

#[derive(Template)]
#[template(path="../static/index.html")] // askama template render engine
struct MyPage {
    content: String
}

#[GET("/a")]
fn foo() {
    html!("<h1>html text!</h1>")
    load!("compile-time static load of html file use include_str! macro")
    template!(MyPage { content: "nice".to_string() })
    // expression of struct. implemented for .render() in askama engine
}

and a one function for parse urls with regex (must run in tokio runtime, what reimported in crate)

let prs; {
    let tokioRuntime = Runtime::new().unwrap();
    prs = tokioRuntime.spawn(parsing(
        "https://your/page/to/parse",
        "<h1>[^<]+</h1>|<h2>[^<]+</h2>|<h3>[^<]+</h3>|<h4>[^<]+</h4>")
    ).await.unwrap();
}
let prs = prs.unwrap();
println!("{:?}", prs);

Reimported crates

actix-web = "3"
regex = "1.5.4"
tokio = { version = "1", features = ["rt", "rt-multi-thread"] }
actix-files = "0.3"

Dependencies

~24–39MB
~698K SLoC