I have a Server struct like so
#[derive(Clone)]
pub struct Server {
address: String,
rpc: RpcHandler,
state: AppState,
}
impl Server {
pub fn new(address: &str, rpc: RpcHandler, state: AppState) -> Self {
Self {
address: address.to_string(),
rpc,
state,
}
}
pub async fn start(&self) -> Result<()> {
let app = Router::new()
.route("/", get(handlers::status_handler))
.route("/json", post(self.clone()))
.with_state(self.state.clone())
.layer(middleware::map_response(handlers::response_handler))
.layer(middleware::from_fn(middlewares::context_resolver));
let listener = tokio::net::TcpListener::bind(&self.address).await.unwrap();
println!("Listening on {}", &listener.local_addr().unwrap());
axum::serve(listener, app.into_make_service())
.await
.unwrap();
Ok(())
}
}
Explanation:
address: URL the Server will be bound onrpc: RpcHandler Struct which contains Rpc commands the server will respond tostate: App state (DB Connection ...)
I've implemented Handler to this struct like so :
impl Handler<Request<Body>, AppState> for Server {
type Future = Pin<Box<dyn Future<Output = Response<Body>> + Send>>;
fn call(self, req: Request<Body>, state: AppState) -> Self::Future {
Box::pin(async move {
// For Test
let result: JsonResult = Ok(Json(json!({ "message": "Hello world" })));
match result {
Ok(json_response) => json_response.into_response(),
Err(error) => {
let error_response = Json(json!({ "error": error.to_string() })).into_response();
error_response
}
}
/*
Expected Behavior
// Extract Context
// Extract Body -> RpcCommand({ command: String, params: (Some Json) })
let rpc_request = // Extracted from body
let rpc_command = match &self.rpc.get_command(rpc_request.name) {
Some(command) => &command.execute(context, state, rpc_request.params).await;
None => // Send CommandNotFoundError
};
*/
})
}
}
I have problems extracting the context (which is resolved by the context_resolver middleware and implements FromRequestParts.
I also want to extract body into Json but don't know how to do it