1

This works where the handler is a stand alone function

use axum::{
    routing::{get, post},
    http::StatusCode,
    response::IntoResponse,
    Json, Router,
};
use std::net::SocketAddr;

#[tokio::main]
async fn main() -> () {

    // build our application with a route
    let app = Router::new()
        // `GET /` goes to `root`
        .route("/", axum::routing::get(root));

    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();

}

// basic handler that responds with a static string
async fn root() -> impl IntoResponse {
    let person = Person {
        age: 20,
        name: "John".to_string()
    };
    (StatusCode::OK, Json(person))
}

but in my project, I need to have the logic of the handler as part of a struct impl. I tried doing that but it fails. Code and error is below

use axum::{
    routing::{get, post},
    http::StatusCode,
    response::IntoResponse,
    Json, Router,
};
use std::net::SocketAddr;

mod http {
    pub struct ServerLogic {
    }

    impl ServerLogic {
        pub fn new() -> Self {
            Self {}
        }
        pub fn hello(&self) -> impl axum::response::IntoResponse {
            (axum::http::StatusCode::OK, axum::Json("Hello, world!"))
        }
    }
}

#[tokio::main]
async fn main() -> () {

    // build our application with a route
    let app = Router::new()
        // `GET /` goes to `root`
        .route("/", axum::routing::get(crate::http::ServerLogic::new().hello));

    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();

}

Error

error[E0615]: attempted to take value of method `hello` on type `ServerLogic`
   --> src/main.rs:104:72
    |
104 |         .route("/", axum::routing::get(crate::http::ServerLogic::new().hello));
    |                                                                        ^^^^^ method, not a field
    |
help: use parentheses to call the method
    |
104 |         .route("/", axum::routing::get(crate::http::ServerLogic::new().hello()));
    |                                                                             ++

How do I get to use the method of a struct as an handler?

Finlay Weber
  • 2,989
  • 3
  • 17
  • 37

0 Answers0