Server

Struct Server 

Source
pub struct Server {
    pub max_connections: usize,
    pub keep_alive: Duration,
    /* private fields */
}
Expand description

The main application struct that represents your web server.

§Example

use axeon::{ok_json, Server};


fn main() {
    let mut app = Server::new();

    // Add a route
    app.get("/", |_req| async {
    ok_json!({ "message": "Hello" })
    });

    // Start the server
    app.listen("127.0.0.1:3000").unwrap();
}

Fields§

§max_connections: usize§keep_alive: Duration

Implementations§

Source§

impl Server

Source

pub fn new() -> Self

Creates a new Application instance

Examples found in repository?
examples/hello_world.rs (line 9)
8fn main() {
9    let mut app = Server::new();
10
11    // Add a route that handles GET requests to "/"
12    app.get("/", |_req| async { Response::text("Hello, World!") });
13
14    app.listen("127.0.0.1:3000")
15        .expect("Server failed to start");
16}
More examples
Hide additional examples
examples/middleware.rs (line 58)
57fn main() {
58    let mut app = Server::new();
59
60    // Apply logger middleware globally
61    app.middleware(Logger);
62
63    // Public route - no auth required
64    app.get("/public", |_req| async  {
65        Response::text("This is a public endpoint")
66    });
67
68    // Protected routes with auth middleware
69    let mut protected = Router::new();
70    protected.middleware(AuthMiddleware);
71
72    protected.get("/profile", |_req| async  {
73        ok_json!({
74            "name": "User",
75            "email": "user@example.com"
76        })
77    });
78
79    app.mount("/api", protected);
80
81    app.listen("127.0.0.1:3000")
82        .expect("Server failed to start");
83}
examples/routing.rs (line 19)
18fn main() {
19    let mut app = Server::new();
20
21    // Basic GET route
22    app.get("/", |_req| async {
23        Response::text("Welcome to Axeon API server!")
24    });
25
26    // Route with path parameter
27    app.get("/users/:id", |req| async move {
28        let user_id = req.params.get("id").unwrap();
29        Response::text(format!("User ID: {}", user_id))
30    });
31
32    // POST request with JSON body
33    app.post("/users", |req| async move {
34        match req.body.json::<User>() {
35            Some(user) => Response::ok(&user),
36            None => Err(ServerError::BadRequest("Invalid JSON body".to_string())),
37        }
38    });
39
40    // Group routes under /api prefix
41    let mut api = Router::new();
42    api.get("/status", |_req| async {
43        Response::ok(&serde_json::json!({
44            "status": "operational",
45            "version": "1.0.0"
46        }))
47    });
48
49    // Mount the API router to the main server
50    app.mount("/api", api);
51
52    app.listen("127.0.0.1:3000")
53        .expect("Server failed to start")
54}
Source

pub fn max_connections(&mut self, max_connections: usize) -> &mut Self

Source

pub fn keep_alive(&mut self, keep_alive: Duration) -> &mut Self

Source

pub fn plugins<T>(&mut self, plugin: T) -> &mut Self
where T: Send + Sync + 'static,

Source

pub fn on_error<F>(&mut self, handler: F) -> &mut Self
where F: Fn(ServerError) -> Response + Send + Sync + 'static,

Source

pub fn get<F, R>(&mut self, path: &str, handler: F)
where F: Fn(Request) -> R + Send + Clone + Sync + 'static, R: IntoResponse + 'static,

Registers a GET route handler

§Arguments
  • path - The URL path to match
  • handler - The async handler function
Examples found in repository?
examples/hello_world.rs (line 12)
8fn main() {
9    let mut app = Server::new();
10
11    // Add a route that handles GET requests to "/"
12    app.get("/", |_req| async { Response::text("Hello, World!") });
13
14    app.listen("127.0.0.1:3000")
15        .expect("Server failed to start");
16}
More examples
Hide additional examples
examples/middleware.rs (lines 64-66)
57fn main() {
58    let mut app = Server::new();
59
60    // Apply logger middleware globally
61    app.middleware(Logger);
62
63    // Public route - no auth required
64    app.get("/public", |_req| async  {
65        Response::text("This is a public endpoint")
66    });
67
68    // Protected routes with auth middleware
69    let mut protected = Router::new();
70    protected.middleware(AuthMiddleware);
71
72    protected.get("/profile", |_req| async  {
73        ok_json!({
74            "name": "User",
75            "email": "user@example.com"
76        })
77    });
78
79    app.mount("/api", protected);
80
81    app.listen("127.0.0.1:3000")
82        .expect("Server failed to start");
83}
examples/routing.rs (lines 22-24)
18fn main() {
19    let mut app = Server::new();
20
21    // Basic GET route
22    app.get("/", |_req| async {
23        Response::text("Welcome to Axeon API server!")
24    });
25
26    // Route with path parameter
27    app.get("/users/:id", |req| async move {
28        let user_id = req.params.get("id").unwrap();
29        Response::text(format!("User ID: {}", user_id))
30    });
31
32    // POST request with JSON body
33    app.post("/users", |req| async move {
34        match req.body.json::<User>() {
35            Some(user) => Response::ok(&user),
36            None => Err(ServerError::BadRequest("Invalid JSON body".to_string())),
37        }
38    });
39
40    // Group routes under /api prefix
41    let mut api = Router::new();
42    api.get("/status", |_req| async {
43        Response::ok(&serde_json::json!({
44            "status": "operational",
45            "version": "1.0.0"
46        }))
47    });
48
49    // Mount the API router to the main server
50    app.mount("/api", api);
51
52    app.listen("127.0.0.1:3000")
53        .expect("Server failed to start")
54}
Source

pub fn post<F, R>(&mut self, path: &str, handler: F)
where F: Fn(Request) -> R + Send + Clone + Sync + 'static, R: IntoResponse + 'static,

Registers a POST route handler

§Arguments
  • path - The URL path to match
  • handler - The async handler function
Examples found in repository?
examples/routing.rs (lines 33-38)
18fn main() {
19    let mut app = Server::new();
20
21    // Basic GET route
22    app.get("/", |_req| async {
23        Response::text("Welcome to Axeon API server!")
24    });
25
26    // Route with path parameter
27    app.get("/users/:id", |req| async move {
28        let user_id = req.params.get("id").unwrap();
29        Response::text(format!("User ID: {}", user_id))
30    });
31
32    // POST request with JSON body
33    app.post("/users", |req| async move {
34        match req.body.json::<User>() {
35            Some(user) => Response::ok(&user),
36            None => Err(ServerError::BadRequest("Invalid JSON body".to_string())),
37        }
38    });
39
40    // Group routes under /api prefix
41    let mut api = Router::new();
42    api.get("/status", |_req| async {
43        Response::ok(&serde_json::json!({
44            "status": "operational",
45            "version": "1.0.0"
46        }))
47    });
48
49    // Mount the API router to the main server
50    app.mount("/api", api);
51
52    app.listen("127.0.0.1:3000")
53        .expect("Server failed to start")
54}
Source

pub fn put<F, R>(&mut self, path: &str, handler: F)
where F: Fn(Request) -> R + Send + Clone + Sync + 'static, R: IntoResponse + 'static,

Registers a PUT route handler

§Arguments
  • path - The URL path to match
  • handler - The async handler function
Source

pub fn patch<F, R>(&mut self, path: &str, handler: F)
where F: Fn(Request) -> R + Send + Clone + Sync + 'static, R: IntoResponse + 'static,

Registers a PATCH route handler

§Arguments
  • path - The URL path to match
  • handler - The async handler function
Source

pub fn delete<F, R>(&mut self, path: &str, handler: F)
where F: Fn(Request) -> R + Send + Clone + Sync + 'static, R: IntoResponse + 'static,

Registers a DELETE route handler

§Arguments
  • path - The URL path to match
  • handler - The async handler function
Source

pub fn head<F, R>(&mut self, path: &str, handler: F)
where F: Fn(Request) -> R + Send + Clone + Sync + 'static, R: IntoResponse + 'static,

Registers a HEAD route handler

§Arguments
  • path - The URL path to match
  • handler - The async handler function
Source

pub fn connect<F, R>(&mut self, path: &str, handler: F)
where F: Fn(Request) -> R + Send + Clone + Sync + 'static, R: IntoResponse + 'static,

Registers a CONNECT route handler

§Arguments
  • path - The URL path to match
  • handler - The async handler function
Source

pub fn options<F, R>(&mut self, path: &str, handler: F)
where F: Fn(Request) -> R + Send + Clone + Sync + 'static, R: IntoResponse + 'static,

Registers an OPTIONS route handler

§Arguments
  • path - The URL path to match
  • handler - The async handler function
Source

pub fn trace<F, R>(&mut self, path: &str, handler: F)
where F: Fn(Request) -> R + Send + Clone + Sync + 'static, R: IntoResponse + 'static,

Registers a TRACE route handler

§Arguments
  • path - The URL path to match
  • handler - The async handler function
Source

pub fn middleware(&mut self, middleware: impl Middleware + 'static)

Adds a middleware to the application

§Arguments
  • middleware - The middleware to add
Examples found in repository?
examples/middleware.rs (line 61)
57fn main() {
58    let mut app = Server::new();
59
60    // Apply logger middleware globally
61    app.middleware(Logger);
62
63    // Public route - no auth required
64    app.get("/public", |_req| async  {
65        Response::text("This is a public endpoint")
66    });
67
68    // Protected routes with auth middleware
69    let mut protected = Router::new();
70    protected.middleware(AuthMiddleware);
71
72    protected.get("/profile", |_req| async  {
73        ok_json!({
74            "name": "User",
75            "email": "user@example.com"
76        })
77    });
78
79    app.mount("/api", protected);
80
81    app.listen("127.0.0.1:3000")
82        .expect("Server failed to start");
83}
Source

pub fn mount(&mut self, path: &str, router: Router)

Mounts a router at a specific path

§Arguments
  • path - The URL path to mount the router
  • router - The router to mount
Examples found in repository?
examples/middleware.rs (line 79)
57fn main() {
58    let mut app = Server::new();
59
60    // Apply logger middleware globally
61    app.middleware(Logger);
62
63    // Public route - no auth required
64    app.get("/public", |_req| async  {
65        Response::text("This is a public endpoint")
66    });
67
68    // Protected routes with auth middleware
69    let mut protected = Router::new();
70    protected.middleware(AuthMiddleware);
71
72    protected.get("/profile", |_req| async  {
73        ok_json!({
74            "name": "User",
75            "email": "user@example.com"
76        })
77    });
78
79    app.mount("/api", protected);
80
81    app.listen("127.0.0.1:3000")
82        .expect("Server failed to start");
83}
More examples
Hide additional examples
examples/routing.rs (line 50)
18fn main() {
19    let mut app = Server::new();
20
21    // Basic GET route
22    app.get("/", |_req| async {
23        Response::text("Welcome to Axeon API server!")
24    });
25
26    // Route with path parameter
27    app.get("/users/:id", |req| async move {
28        let user_id = req.params.get("id").unwrap();
29        Response::text(format!("User ID: {}", user_id))
30    });
31
32    // POST request with JSON body
33    app.post("/users", |req| async move {
34        match req.body.json::<User>() {
35            Some(user) => Response::ok(&user),
36            None => Err(ServerError::BadRequest("Invalid JSON body".to_string())),
37        }
38    });
39
40    // Group routes under /api prefix
41    let mut api = Router::new();
42    api.get("/status", |_req| async {
43        Response::ok(&serde_json::json!({
44            "status": "operational",
45            "version": "1.0.0"
46        }))
47    });
48
49    // Mount the API router to the main server
50    app.mount("/api", api);
51
52    app.listen("127.0.0.1:3000")
53        .expect("Server failed to start")
54}
Source

pub fn with_tls<P: AsRef<Path>>( &mut self, cert_file: P, key_file: P, ) -> &mut Self

Configure TLS for HTTPS support

Source

pub fn listen(self, addr: &str) -> Result<(), Box<dyn Error>>

Starts the HTTP server

§Arguments
  • addr - Address to listen on (e.g. “127.0.0.1:3000”)
Examples found in repository?
examples/hello_world.rs (line 14)
8fn main() {
9    let mut app = Server::new();
10
11    // Add a route that handles GET requests to "/"
12    app.get("/", |_req| async { Response::text("Hello, World!") });
13
14    app.listen("127.0.0.1:3000")
15        .expect("Server failed to start");
16}
More examples
Hide additional examples
examples/middleware.rs (line 81)
57fn main() {
58    let mut app = Server::new();
59
60    // Apply logger middleware globally
61    app.middleware(Logger);
62
63    // Public route - no auth required
64    app.get("/public", |_req| async  {
65        Response::text("This is a public endpoint")
66    });
67
68    // Protected routes with auth middleware
69    let mut protected = Router::new();
70    protected.middleware(AuthMiddleware);
71
72    protected.get("/profile", |_req| async  {
73        ok_json!({
74            "name": "User",
75            "email": "user@example.com"
76        })
77    });
78
79    app.mount("/api", protected);
80
81    app.listen("127.0.0.1:3000")
82        .expect("Server failed to start");
83}
examples/routing.rs (line 52)
18fn main() {
19    let mut app = Server::new();
20
21    // Basic GET route
22    app.get("/", |_req| async {
23        Response::text("Welcome to Axeon API server!")
24    });
25
26    // Route with path parameter
27    app.get("/users/:id", |req| async move {
28        let user_id = req.params.get("id").unwrap();
29        Response::text(format!("User ID: {}", user_id))
30    });
31
32    // POST request with JSON body
33    app.post("/users", |req| async move {
34        match req.body.json::<User>() {
35            Some(user) => Response::ok(&user),
36            None => Err(ServerError::BadRequest("Invalid JSON body".to_string())),
37        }
38    });
39
40    // Group routes under /api prefix
41    let mut api = Router::new();
42    api.get("/status", |_req| async {
43        Response::ok(&serde_json::json!({
44            "status": "operational",
45            "version": "1.0.0"
46        }))
47    });
48
49    // Mount the API router to the main server
50    app.mount("/api", api);
51
52    app.listen("127.0.0.1:3000")
53        .expect("Server failed to start")
54}
Source

pub fn static_dir(&mut self, dir: &str) -> &mut Self

Sets the directory for serving static files

§Arguments
  • dir - Path to the static files directory
§Example

use axeon::Server;

let mut app = Server::new();
app.static_dir("public");

Trait Implementations§

Source§

impl Clone for Server

Source§

fn clone(&self) -> Server

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

§

impl Freeze for Server

§

impl !RefUnwindSafe for Server

§

impl Send for Server

§

impl Sync for Server

§

impl Unpin for Server

§

impl !UnwindSafe for Server

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.