Error while calling the function

This is the error I'm unable to call the method in main function

error[E0599]: no method named to found for reference &'static str in the current scope
--> src/main.rs:48:44
|
48 | .service(web::resource("/we".to(finally())))
| ^^ method not found in &'static str

main.rs

 HttpServer::new(|| {
      App::new()
         // .service(web::resource("/roy").to(finally()))

          .service(web::resource("/benstokes").to(will_win))
          .service(web::resource("/we".to(finally())))


 })

database2.rs

This file contains the database part and the data to be sent to html file using handlers

use std::fs;
use handlebars::{Handlebars, Renderable};
use sqlx::postgres::PgPoolOptions;
use serde_json::json;
use sqlx::Error;
use serde::Serialize;

#[derive(sqlx::FromRow)]
#[derive(Serialize)]
struct User {
title: String,
description: String,
name: String,
}

pub async fn one_final_page( users: Vec){

let mut handlebars = Handlebars::new();
let template_source = "templates/index1.hbs" ;
let template = handlebars::Template::compile(template_source);

let context = json!({
"users": users,

});
let html = handlebars.render_template(template_source, &context);

}

pub async fn finally() ->Result<(),Error>{

dotenv::dotenv().expect("Unable to load environment variables from .env file");

let db_url = std::env::var("DATABASE_URL").expect("Unable to read DATABASE_URL env var");

let mut pool = PgPoolOptions::new()
    .max_connections(100)
    .connect(&db_url)
    .await.expect("Unable to connect to Postgres");

let query = sqlx::queryas::<, User>("SELECT title,description ,name FROM posts");
let users: Vec<User> = query.fetch_all(&pool).await?;


for user in &users {
    println!("{}{}{}", user.title, user.description,user.name);
}

one_final_page(users).await;

Ok(())

Looks like you closed the brackets wrongly in this line:

-    .service(web::resource("/we".to(finally())))
+    .service(web::resource("/we").to(finally()))
2 Likes

I tried this but it is not working

https://github.dev/MohanSharmav/blog_rust_2

Please check this and help me

| help: remove this mut

error[E0277]: the trait bound impl warp::Future<Output = Result<(), sqlx::Error>>: Handler<_> is not satisfied
--> src/main.rs:56:50
|
56 | .service(web::resource("/king").to(England()))
| -- ^^^^^^^^^ the trait Handler<_> is not implemented for impl warp::Future<Output = Result<(), sqlx::Error>>
| |
| required by a bound introduced by this call
|
note: required by a bound in Resource::<T>::to
--> /Users/mohanvenkatesh/.cargo/registry/src/github.com-1ecc6299db9ec823/actix-web-4.3.1/src/resource.rs:240:12
|
240 | F: Handler,
| ^^^^^^^^^^^^^ required by this bound in Resource::<T>::to

For more information about this error, try rustc --explain E0277.
warning: blog (bin "blog") generated 37 warnings
error: could not compile blog due to previous error; 3

    HttpResponse::Ok()
        .content_type("text/html; charset=utf-8")
        .body(html);

Ok(())

Try returning the HttpResponse from your endpoint, otherwise it won't do anything. Ok(()) does not implement Responder. Endpoints in actix must have a return type that implements Responder. sqlx::Error also does not implement Into<actix_web::error::Error> nor ResponseError (required for Result<T, E> to implement Responder). Unfortunately you can't just implement ResponseError for sqlx::Error (foreign trait on foreign type), so you have to wrap it in your own error.

Here a basic change that compiles:

#[derive(Debug)]
pub struct DbError;

impl From<Error> for DbError {
    fn from(e: Error) -> Self {
        Self
    }
}

impl std::fmt::Display for DbError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "DbError")
    }
}

impl actix_web::error::ResponseError for DbError {}

pub async fn England()->Result<HttpResponse, DbError> {
        // leave rest of function unchanged

        Ok(HttpResponse::Ok()
            .content_type("text/html; charset=utf-8")
            .body(html))
}

and in your main function provide England as a function directly, without calling it:

-               .service(web::resource("/king").to(England()))`
+               .service(web::resource("/king").to(England))

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.