Skip to main content

app

Function app 

Source
pub fn app() -> App
Expand description

Creates a new Express-style application instance.

This is the main entry-point for the framework, equivalent to calling express() in Node.js.

ยงExample

use expressjs::prelude::*;

#[expressjs::main]
async fn main() {
    let mut app = express();
    app.get("/", async |_req, res| res.send_text("Hello, world!"));
    app.listen(3000, async |port| println!("Listening on port {port}")).await;
}

Initializes a new express application.

Examples found in repository?
examples/hello_world.rs (line 5)
4async fn main() {
5    let mut app = express();
6
7    app.get("/", async |_req, res| res.send_text("Hello World!"));
8
9    app.listen(9000, async |port| {
10        println!("๐Ÿš€ Server running on http://localhost:{port}/");
11    })
12    .await;
13}
More examples
Hide additional examples
examples/json.rs (line 6)
5async fn main() {
6    let mut app = express();
7
8    app.get("/json", async |_req, res| {
9        res.send_json(&json!({
10            "status": "success",
11            "message": "Hello from JSON!",
12            "data": {
13                "id": 1,
14                "name": "Aragorn",
15                "role": "King"
16            }
17        }))
18    });
19
20    app.listen(9000, async |port| {
21        println!("๐Ÿš€ Server running on http://localhost:{port}/json");
22    })
23    .await;
24}
examples/routing.rs (line 5)
4async fn main() {
5    let mut app = express();
6
7    // Static route
8    app.get("/", async |_req, res| res.send_text("Welcome!"));
9
10    // Route with one parameter
11    app.get("/users/{id}", async |req, res| {
12        let id = req.params().get("id").unwrap_or("unknown");
13        res.send_text(format!("User ID: {id}"))
14    });
15
16    // Route with multiple parameters
17    app.get(
18        "/posts/{post_id}/comments/{comment_id}",
19        async |req, res| {
20            let post_id = req.params().get("post_id").unwrap_or("unknown");
21            let comment_id = req.params().get("comment_id").unwrap_or("unknown");
22            res.send_text(format!("Post ID: {post_id}, Comment ID: {comment_id}"))
23        },
24    );
25
26    // Catch-all (glob)
27    app.get("/static/{*path}", async |req, res| {
28        let path = req.params().get("path").unwrap_or("");
29        res.send_text(format!("Serving file from: {path}"))
30    });
31
32    app.listen(9000, async |port| {
33        println!("๐Ÿš€ Server running on http://localhost:{port}/");
34    })
35    .await;
36}
examples/middleware.rs (line 6)
5async fn main() {
6    let mut app = express();
7
8    // Global middleware: Cors
9    app.use_global(CorsMiddleware::permissive());
10
11    // Global middleware: Normalize path
12    app.use_global(NormalizePathMiddleware::new());
13
14    // Route-specific middleware (using prefix)
15    app.use_with("/api", |req: &mut Request, _res: &mut Response| {
16        let path = req.uri().path().to_owned();
17        async move {
18            println!("API middleware triggered for: {}", path);
19            next_res()
20        }
21    });
22
23    app.get("/api/v1", async |_req, res| res.send_text("API Response"));
24
25    // Header manipulation in middleware (global logging)
26    app.use_global(LoggingMiddleware);
27
28    // Dynamic middleware logic
29    app.use_global(|req: &mut Request, res: &mut Response| {
30        let uri = req.uri().to_string();
31        res.header("X-Custom-Global", HeaderValue::from_static("Enabled"));
32        async move {
33            println!("Custom global middleware for: {}", uri);
34            next_res()
35        }
36    });
37
38    app.get("/hello", async |_req, res| res.send_text("Hello!"));
39
40    app.listen(9000, async |port| {
41        println!("๐Ÿš€ Server running on http://localhost:{port}/");
42    })
43    .await;
44}
examples/basic.rs (line 37)
33async fn main() {
34    setup_logger().unwrap();
35
36    const PORT: u16 = 9000;
37    let mut app = express();
38
39    // Middleware
40    app.use_global(NormalizePathMiddleware::new())
41        .use_global(CorsMiddleware::permissive())
42        .use_global(LoggingMiddleware)
43        .use_with("/css/{*p}", StaticServeMiddleware::new("."))
44        .use_with("/expressjs_tests/{*p}", StaticServeMiddleware::new("."));
45
46    // Routes
47
48    // GET / - index page
49    app.get("/", async |_req, res| {
50        let html = r#"
51        <!DOCTYPE html>
52        <html lang="en">
53        <head>
54            <meta charset="UTF-8">
55            <meta name="viewport" content="width=device-width, initial-scale=1.0">
56            <title>Welcome</title>
57            <link rel="stylesheet" href="/css/index.css"/>
58        </head>
59        <body>
60            <h1>Welcome to expressjs</h1>
61            <p>This is a minimal HTML page served from Rust.</p>
62            <ul>
63                <li><a href="/json">JSON Endpoint</a></li>
64                <li><a href="/redirect">Redirect to Home</a></li>
65                <li><a href="status">Trigger 400</a></li>
66                <li><a href="hello">Say Hello</a></li>
67            </ul>
68        </body>
69        </html>
70        "#;
71
72        res.status_code(200)
73            .content_type("text/html; charset=utf-8")
74            .send_html(html)
75    });
76
77    // GET /count - request counter
78    app.get("/count", async |_req, res| {
79        let count = STATE.request_count.fetch_add(1, Ordering::Relaxed);
80
81        res.send_json(&json!({
82            "request_count": count,
83            "message": "Request count retrieved successfully"
84        }))
85    });
86
87    // GET /json - static JSON response
88    app.get("/json", async |_req, res| {
89        res.header(
90            hyper::header::CACHE_CONTROL,
91            HeaderValue::from_static("public, max-age=3600"),
92        )
93        .send_json(&json!({
94            "message": "Hello from JSON!",
95            "status": "success",
96            "version": "1.0"
97        }))
98    });
99
100    // GET /redirect - redirect to /
101    app.get("/redirect", async |_req, res| res.redirect("/"));
102
103    // GET /status - always 400
104    app.get("/status", async |_req, res| {
105        res.status_code(400).send_text("400 Bad Request")
106    });
107
108    // GET /status/:status - echo status param
109    app.get("/status/{status}", async |req, res| {
110        let value = req.params().get("status").unwrap_or("unknown");
111        res.send_text(format!("Status is {value}"))
112    });
113
114    // GET /file - stream Cargo.lock (async, borrows res across await)
115    app.get("/file", async |_req, res| {
116        res.send_file("./Cargo.lock").await
117    });
118
119    // /hello - X-Powered-By middleware then response
120    // app.use_with("/hello", async |_req: &mut Request, res: &mut Response| {
121    //     res.header("x-powered-by", HeaderValue::from_static("DevYatsu"));
122    //     stop_res()
123    // });
124
125    app.get("/hello", async |_req, res| {
126        res.body("Hello, world!")
127            .header(
128                header::CACHE_CONTROL,
129                HeaderValue::from_static("public, max-age=86400"),
130            )
131            .header(header::CONTENT_TYPE, HeaderValue::from_static("text/html"))
132    });
133
134    // Route builder pattern - multiple methods on the same path
135    app.route("/api/v1/user")
136        .get(async |_req, res| res.send_text("Get User"))
137        .post(async |_req, res| res.send_text("Post User"));
138
139    // all() - matches every HTTP method
140    app.all("/ping", async |_req, res| res.send_text("pong"));
141
142    // Custom 404 handler
143    app.not_found(async |_req, res| {
144        res.status_code(404)
145            .send_text("Custom 404: Page not found!")
146    });
147
148    // Listen
149    app.listen(PORT, async |port| {
150        let local_ip = local_ip().unwrap();
151        info!("๐Ÿš€ Server running!");
152        info!("๐Ÿ“ Local:   http://localhost:{port}/");
153        info!("๐ŸŒ Network: http://{local_ip}:{port}/");
154    })
155    .await
156}