0

I am new to Rust as Backend developer. So I dont know which web library today is the best. So I choose not to worry about that but make a wrapper for the web library.

To do so, First thing I need to do is, not let the library to ruin all of my code which mean non of the type of the library should be seen in my other rust file instead in a single rust file. That can make me easily to replace the web library if there is some problem of the library happend.

Here is my abstraction of Server

use crate::server::router::Response;
use crate::server::router::{Request, Router};

use std::fmt::{Debug};

#[derive(Debug)]
pub struct Server {
    pub(crate) port: i32,
}

pub trait ServerActions {
    fn get_routers(
        self: &Self,
    ) -> Vec<Box<Router>>;
    fn get_middleware_on_request(
        self: &Self,
    ) -> Vec<fn(req: Request) -> Request>;

    fn get_middleware_on_response(
        self: &Self,
    ) -> Vec<fn(res: Response) -> Response>;
}

impl ServerActions for Server {
    fn get_routers(self: &Self) -> Vec<Box<Router>> {
        todo!()
    }

    fn get_middleware_on_request(self: &Self) -> Vec<fn(Request) -> Request> {
        todo!()
    }

    fn get_middleware_on_response(self: &Self) -> Vec<fn(Response) -> Response> {
        todo!()
    }
}

And here is a abstraction for the Web library:

use async_trait::async_trait;

#[async_trait]
pub trait Web {
    async fn start(self: &Self);
}

And inside the 'axum.rs' file I need to implement the Web trait for the Server

use crate::server::server::Server;
use crate::web_frameworks::web::Web;

impl Web for Server {
    async fn start(self: &Self) {
        let routers = self.get_routers();
        for router in routers  {
            //add my own router to Axum
            
        }
    }
}

And then I can start my web server in main just like this:

let server = &mut Server{
        port: 8080
    };
server.start().await;

So, my question is, how do I map the routers of Server.getRouters() to Axum? The things is I need to convert the request body to my own RequestBody and the Headers to my Own Headers.

The type of the Router is

pub struct Request {
    pub current_user_id: String,
    pub body: String,
    pub headers: HashMap<String, String>,
}

pub type Handler = fn(req: Request, db: &DB) -> Response;

pub struct Router {
    pub(crate) path: String,
    pub(crate) method: RouterMethod,
    pub(crate) router_handler: Handler,
}

Which mean I need to pass a Request structure and a DB reference? The problem is I dont know how to get the Request structure from Axum. Thanks.

Ma Zheng
  • 11
  • 2

0 Answers0