Lifetime issue with Actix Web












1















I'm implementing middleware with Actix-web and having an issue with lifetime that I couldn't figure out.



extern crate actix_web;

use actix_web::actix::{Actor, Addr, Context, System};
use actix_web::middleware::Middleware;
use actix_web::{http, server, App, HttpRequest, Responder};
use std::collections::HashMap;

pub struct CacheActor {
caches: HashMap<String, String>,
}

impl CacheActor {
pub fn new() -> Self {
CacheActor {
caches: HashMap::new(),
}
}
}

impl Actor for CacheActor {
type Context = Context<Self>;
}

fn create_resource(req: HttpRequest, addr: &Addr<CacheActor>) -> impl Responder {
unimplemented!();
format!("Unimplemented")
}

fn list_resources(req: HttpRequest, addr: &Addr<CacheActor>) -> impl Responder {
unimplemented!();
format!("Unimplemented")
}

pub trait TusMiddlewareTrait {
fn with_tus(self, addr: &Addr<CacheActor>) -> App;
}

impl TusMiddlewareTrait for App {
fn with_tus(self, addr: &Addr<CacheActor>) -> App {
self.route("/files", http::Method::GET, |req| list_resources(req, addr))
.route("/files", http::Method::POST, |req| {
create_resource(req, addr)
})
}
}

fn main() {
let system = System::new("Example");
let cache_addr = CacheActor::new().start();

server::new(|| App::new().with_tus(&cache_addr))
.bind("127.0.0.1:8080")
.unwrap()
.run();

system.run();
}


The error that I get is the following,



error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/tus/middleware.rs:84:49
|
84 | .route("/files", http::Method::GET, |req| list_resources(req, addr))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 81:5...
--> src/tus/middleware.rs:81:5
|
81 | / fn with_tus(self, addr: &actix::Addr<cache::CacheActor>) -> App {
82 | | self.middleware(TusMiddleware)
83 | | .route("/files", http::Method::OPTIONS, tus_information)
84 | | .route("/files", http::Method::GET, |req| list_resources(req, addr))
... |
87 | | })
88 | | }
| |_____^
= note: ...so that the types are compatible:
expected &&actix::address::Addr<tus::cache::CacheActor>
found &&actix::address::Addr<tus::cache::CacheActor>
= note: but, the lifetime must be valid for the static lifetime...


As for what I understand, I am passing cache_addr as a reference to with_tus function. Inside each closure in route, addr is also a reference.



I don't understand why the compiler said the lifetime cannot outlive the anonymous lifetime #1. From what I can tell is that cache_addr's lifetime still outlives the closure. The lifetime should cover up until system.run() line. Can someone enlighten me?



Edit:



I updated the code above to MCVE (at least to a point that it is simple enough to copy the whole code and run cargo build while still preserving the same error message). I can't run it on rust-playground. It doesn't support actix crate at this point. I tried reducing it further but it's giving me a different error. Sorry, I am pretty new to Rust.



My questions are twofold, one I like to understand what's the error telling me. Second, I like to know how to properly do this with actix thus why the sample code is dependent on actix.










share|improve this question





























    1















    I'm implementing middleware with Actix-web and having an issue with lifetime that I couldn't figure out.



    extern crate actix_web;

    use actix_web::actix::{Actor, Addr, Context, System};
    use actix_web::middleware::Middleware;
    use actix_web::{http, server, App, HttpRequest, Responder};
    use std::collections::HashMap;

    pub struct CacheActor {
    caches: HashMap<String, String>,
    }

    impl CacheActor {
    pub fn new() -> Self {
    CacheActor {
    caches: HashMap::new(),
    }
    }
    }

    impl Actor for CacheActor {
    type Context = Context<Self>;
    }

    fn create_resource(req: HttpRequest, addr: &Addr<CacheActor>) -> impl Responder {
    unimplemented!();
    format!("Unimplemented")
    }

    fn list_resources(req: HttpRequest, addr: &Addr<CacheActor>) -> impl Responder {
    unimplemented!();
    format!("Unimplemented")
    }

    pub trait TusMiddlewareTrait {
    fn with_tus(self, addr: &Addr<CacheActor>) -> App;
    }

    impl TusMiddlewareTrait for App {
    fn with_tus(self, addr: &Addr<CacheActor>) -> App {
    self.route("/files", http::Method::GET, |req| list_resources(req, addr))
    .route("/files", http::Method::POST, |req| {
    create_resource(req, addr)
    })
    }
    }

    fn main() {
    let system = System::new("Example");
    let cache_addr = CacheActor::new().start();

    server::new(|| App::new().with_tus(&cache_addr))
    .bind("127.0.0.1:8080")
    .unwrap()
    .run();

    system.run();
    }


    The error that I get is the following,



    error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
    --> src/tus/middleware.rs:84:49
    |
    84 | .route("/files", http::Method::GET, |req| list_resources(req, addr))
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
    note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 81:5...
    --> src/tus/middleware.rs:81:5
    |
    81 | / fn with_tus(self, addr: &actix::Addr<cache::CacheActor>) -> App {
    82 | | self.middleware(TusMiddleware)
    83 | | .route("/files", http::Method::OPTIONS, tus_information)
    84 | | .route("/files", http::Method::GET, |req| list_resources(req, addr))
    ... |
    87 | | })
    88 | | }
    | |_____^
    = note: ...so that the types are compatible:
    expected &&actix::address::Addr<tus::cache::CacheActor>
    found &&actix::address::Addr<tus::cache::CacheActor>
    = note: but, the lifetime must be valid for the static lifetime...


    As for what I understand, I am passing cache_addr as a reference to with_tus function. Inside each closure in route, addr is also a reference.



    I don't understand why the compiler said the lifetime cannot outlive the anonymous lifetime #1. From what I can tell is that cache_addr's lifetime still outlives the closure. The lifetime should cover up until system.run() line. Can someone enlighten me?



    Edit:



    I updated the code above to MCVE (at least to a point that it is simple enough to copy the whole code and run cargo build while still preserving the same error message). I can't run it on rust-playground. It doesn't support actix crate at this point. I tried reducing it further but it's giving me a different error. Sorry, I am pretty new to Rust.



    My questions are twofold, one I like to understand what's the error telling me. Second, I like to know how to properly do this with actix thus why the sample code is dependent on actix.










    share|improve this question



























      1












      1








      1








      I'm implementing middleware with Actix-web and having an issue with lifetime that I couldn't figure out.



      extern crate actix_web;

      use actix_web::actix::{Actor, Addr, Context, System};
      use actix_web::middleware::Middleware;
      use actix_web::{http, server, App, HttpRequest, Responder};
      use std::collections::HashMap;

      pub struct CacheActor {
      caches: HashMap<String, String>,
      }

      impl CacheActor {
      pub fn new() -> Self {
      CacheActor {
      caches: HashMap::new(),
      }
      }
      }

      impl Actor for CacheActor {
      type Context = Context<Self>;
      }

      fn create_resource(req: HttpRequest, addr: &Addr<CacheActor>) -> impl Responder {
      unimplemented!();
      format!("Unimplemented")
      }

      fn list_resources(req: HttpRequest, addr: &Addr<CacheActor>) -> impl Responder {
      unimplemented!();
      format!("Unimplemented")
      }

      pub trait TusMiddlewareTrait {
      fn with_tus(self, addr: &Addr<CacheActor>) -> App;
      }

      impl TusMiddlewareTrait for App {
      fn with_tus(self, addr: &Addr<CacheActor>) -> App {
      self.route("/files", http::Method::GET, |req| list_resources(req, addr))
      .route("/files", http::Method::POST, |req| {
      create_resource(req, addr)
      })
      }
      }

      fn main() {
      let system = System::new("Example");
      let cache_addr = CacheActor::new().start();

      server::new(|| App::new().with_tus(&cache_addr))
      .bind("127.0.0.1:8080")
      .unwrap()
      .run();

      system.run();
      }


      The error that I get is the following,



      error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
      --> src/tus/middleware.rs:84:49
      |
      84 | .route("/files", http::Method::GET, |req| list_resources(req, addr))
      | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      |
      note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 81:5...
      --> src/tus/middleware.rs:81:5
      |
      81 | / fn with_tus(self, addr: &actix::Addr<cache::CacheActor>) -> App {
      82 | | self.middleware(TusMiddleware)
      83 | | .route("/files", http::Method::OPTIONS, tus_information)
      84 | | .route("/files", http::Method::GET, |req| list_resources(req, addr))
      ... |
      87 | | })
      88 | | }
      | |_____^
      = note: ...so that the types are compatible:
      expected &&actix::address::Addr<tus::cache::CacheActor>
      found &&actix::address::Addr<tus::cache::CacheActor>
      = note: but, the lifetime must be valid for the static lifetime...


      As for what I understand, I am passing cache_addr as a reference to with_tus function. Inside each closure in route, addr is also a reference.



      I don't understand why the compiler said the lifetime cannot outlive the anonymous lifetime #1. From what I can tell is that cache_addr's lifetime still outlives the closure. The lifetime should cover up until system.run() line. Can someone enlighten me?



      Edit:



      I updated the code above to MCVE (at least to a point that it is simple enough to copy the whole code and run cargo build while still preserving the same error message). I can't run it on rust-playground. It doesn't support actix crate at this point. I tried reducing it further but it's giving me a different error. Sorry, I am pretty new to Rust.



      My questions are twofold, one I like to understand what's the error telling me. Second, I like to know how to properly do this with actix thus why the sample code is dependent on actix.










      share|improve this question
















      I'm implementing middleware with Actix-web and having an issue with lifetime that I couldn't figure out.



      extern crate actix_web;

      use actix_web::actix::{Actor, Addr, Context, System};
      use actix_web::middleware::Middleware;
      use actix_web::{http, server, App, HttpRequest, Responder};
      use std::collections::HashMap;

      pub struct CacheActor {
      caches: HashMap<String, String>,
      }

      impl CacheActor {
      pub fn new() -> Self {
      CacheActor {
      caches: HashMap::new(),
      }
      }
      }

      impl Actor for CacheActor {
      type Context = Context<Self>;
      }

      fn create_resource(req: HttpRequest, addr: &Addr<CacheActor>) -> impl Responder {
      unimplemented!();
      format!("Unimplemented")
      }

      fn list_resources(req: HttpRequest, addr: &Addr<CacheActor>) -> impl Responder {
      unimplemented!();
      format!("Unimplemented")
      }

      pub trait TusMiddlewareTrait {
      fn with_tus(self, addr: &Addr<CacheActor>) -> App;
      }

      impl TusMiddlewareTrait for App {
      fn with_tus(self, addr: &Addr<CacheActor>) -> App {
      self.route("/files", http::Method::GET, |req| list_resources(req, addr))
      .route("/files", http::Method::POST, |req| {
      create_resource(req, addr)
      })
      }
      }

      fn main() {
      let system = System::new("Example");
      let cache_addr = CacheActor::new().start();

      server::new(|| App::new().with_tus(&cache_addr))
      .bind("127.0.0.1:8080")
      .unwrap()
      .run();

      system.run();
      }


      The error that I get is the following,



      error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
      --> src/tus/middleware.rs:84:49
      |
      84 | .route("/files", http::Method::GET, |req| list_resources(req, addr))
      | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      |
      note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 81:5...
      --> src/tus/middleware.rs:81:5
      |
      81 | / fn with_tus(self, addr: &actix::Addr<cache::CacheActor>) -> App {
      82 | | self.middleware(TusMiddleware)
      83 | | .route("/files", http::Method::OPTIONS, tus_information)
      84 | | .route("/files", http::Method::GET, |req| list_resources(req, addr))
      ... |
      87 | | })
      88 | | }
      | |_____^
      = note: ...so that the types are compatible:
      expected &&actix::address::Addr<tus::cache::CacheActor>
      found &&actix::address::Addr<tus::cache::CacheActor>
      = note: but, the lifetime must be valid for the static lifetime...


      As for what I understand, I am passing cache_addr as a reference to with_tus function. Inside each closure in route, addr is also a reference.



      I don't understand why the compiler said the lifetime cannot outlive the anonymous lifetime #1. From what I can tell is that cache_addr's lifetime still outlives the closure. The lifetime should cover up until system.run() line. Can someone enlighten me?



      Edit:



      I updated the code above to MCVE (at least to a point that it is simple enough to copy the whole code and run cargo build while still preserving the same error message). I can't run it on rust-playground. It doesn't support actix crate at this point. I tried reducing it further but it's giving me a different error. Sorry, I am pretty new to Rust.



      My questions are twofold, one I like to understand what's the error telling me. Second, I like to know how to properly do this with actix thus why the sample code is dependent on actix.







      rust lifetime rust-actix






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 26 '18 at 9:48









      hellow

      5,27242242




      5,27242242










      asked Nov 25 '18 at 7:36









      Shulhi SapliShulhi Sapli

      71611022




      71611022
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Look at the App::route signature:



          pub fn route<T, F, R>(self, path: &str, method: Method, f: F) -> App<S> 
          where
          F: WithFactory<T, S, R>,
          R: Responder + 'static,
          T: FromRequest<S> + 'static,


          F generic depends on T and R that in turn have 'static lifetime requirement.



          Your closure captures an &Addr<CacheActor> that it is not valid for 'static lifetime and this generates the error.



          A possibility that I see is to use the App "State", directly from the docs:




          Application state is shared with all routes and resources within the same application. When using an http actor, state can be accessed with the HttpRequest::state() as read-only, but interior mutability with RefCell can be used to achieve state mutability. State is also available for route matching predicates and middlewares.




          In this case should be something like:



          extern crate actix_web;

          use actix_web::actix::{Actor, Addr, Context, System};
          use actix_web::{http, server, App, HttpRequest, HttpResponse, Result};
          use std::collections::HashMap;
          use actix_web::dev::Handler;

          #[derive(Clone)]
          pub struct CacheActor {
          caches: HashMap<String, String>,
          }

          impl CacheActor {
          pub fn new() -> Self {
          CacheActor {
          caches: HashMap::new(),
          }
          }
          }

          impl Actor for CacheActor {
          type Context = Context<Self>;
          }

          impl<S> Handler<S> for CacheActor {
          type Result = String;

          fn handle(&self, _req: &HttpRequest<S>) -> Self::Result {
          unimplemented!();
          }
          }

          fn list_resources(req: &HttpRequest<Addr<CacheActor>>) -> Result<HttpResponse> {
          Ok(HttpResponse::Found()
          .header(http::header::LOCATION, format!("hello {}", req.path()))
          .finish())
          }

          fn main() {
          let system = System::new("Example");

          server::new(|| {
          let cache_addr = CacheActor::new().start();
          App::with_state(cache_addr)
          .resource("/world", |r| r.method(http::Method::GET).f(list_resources))
          })
          .bind("127.0.0.1:8080")
          .unwrap()
          .run();

          system.run();
          }





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53465548%2flifetime-issue-with-actix-web%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Look at the App::route signature:



            pub fn route<T, F, R>(self, path: &str, method: Method, f: F) -> App<S> 
            where
            F: WithFactory<T, S, R>,
            R: Responder + 'static,
            T: FromRequest<S> + 'static,


            F generic depends on T and R that in turn have 'static lifetime requirement.



            Your closure captures an &Addr<CacheActor> that it is not valid for 'static lifetime and this generates the error.



            A possibility that I see is to use the App "State", directly from the docs:




            Application state is shared with all routes and resources within the same application. When using an http actor, state can be accessed with the HttpRequest::state() as read-only, but interior mutability with RefCell can be used to achieve state mutability. State is also available for route matching predicates and middlewares.




            In this case should be something like:



            extern crate actix_web;

            use actix_web::actix::{Actor, Addr, Context, System};
            use actix_web::{http, server, App, HttpRequest, HttpResponse, Result};
            use std::collections::HashMap;
            use actix_web::dev::Handler;

            #[derive(Clone)]
            pub struct CacheActor {
            caches: HashMap<String, String>,
            }

            impl CacheActor {
            pub fn new() -> Self {
            CacheActor {
            caches: HashMap::new(),
            }
            }
            }

            impl Actor for CacheActor {
            type Context = Context<Self>;
            }

            impl<S> Handler<S> for CacheActor {
            type Result = String;

            fn handle(&self, _req: &HttpRequest<S>) -> Self::Result {
            unimplemented!();
            }
            }

            fn list_resources(req: &HttpRequest<Addr<CacheActor>>) -> Result<HttpResponse> {
            Ok(HttpResponse::Found()
            .header(http::header::LOCATION, format!("hello {}", req.path()))
            .finish())
            }

            fn main() {
            let system = System::new("Example");

            server::new(|| {
            let cache_addr = CacheActor::new().start();
            App::with_state(cache_addr)
            .resource("/world", |r| r.method(http::Method::GET).f(list_resources))
            })
            .bind("127.0.0.1:8080")
            .unwrap()
            .run();

            system.run();
            }





            share|improve this answer




























              0














              Look at the App::route signature:



              pub fn route<T, F, R>(self, path: &str, method: Method, f: F) -> App<S> 
              where
              F: WithFactory<T, S, R>,
              R: Responder + 'static,
              T: FromRequest<S> + 'static,


              F generic depends on T and R that in turn have 'static lifetime requirement.



              Your closure captures an &Addr<CacheActor> that it is not valid for 'static lifetime and this generates the error.



              A possibility that I see is to use the App "State", directly from the docs:




              Application state is shared with all routes and resources within the same application. When using an http actor, state can be accessed with the HttpRequest::state() as read-only, but interior mutability with RefCell can be used to achieve state mutability. State is also available for route matching predicates and middlewares.




              In this case should be something like:



              extern crate actix_web;

              use actix_web::actix::{Actor, Addr, Context, System};
              use actix_web::{http, server, App, HttpRequest, HttpResponse, Result};
              use std::collections::HashMap;
              use actix_web::dev::Handler;

              #[derive(Clone)]
              pub struct CacheActor {
              caches: HashMap<String, String>,
              }

              impl CacheActor {
              pub fn new() -> Self {
              CacheActor {
              caches: HashMap::new(),
              }
              }
              }

              impl Actor for CacheActor {
              type Context = Context<Self>;
              }

              impl<S> Handler<S> for CacheActor {
              type Result = String;

              fn handle(&self, _req: &HttpRequest<S>) -> Self::Result {
              unimplemented!();
              }
              }

              fn list_resources(req: &HttpRequest<Addr<CacheActor>>) -> Result<HttpResponse> {
              Ok(HttpResponse::Found()
              .header(http::header::LOCATION, format!("hello {}", req.path()))
              .finish())
              }

              fn main() {
              let system = System::new("Example");

              server::new(|| {
              let cache_addr = CacheActor::new().start();
              App::with_state(cache_addr)
              .resource("/world", |r| r.method(http::Method::GET).f(list_resources))
              })
              .bind("127.0.0.1:8080")
              .unwrap()
              .run();

              system.run();
              }





              share|improve this answer


























                0












                0








                0







                Look at the App::route signature:



                pub fn route<T, F, R>(self, path: &str, method: Method, f: F) -> App<S> 
                where
                F: WithFactory<T, S, R>,
                R: Responder + 'static,
                T: FromRequest<S> + 'static,


                F generic depends on T and R that in turn have 'static lifetime requirement.



                Your closure captures an &Addr<CacheActor> that it is not valid for 'static lifetime and this generates the error.



                A possibility that I see is to use the App "State", directly from the docs:




                Application state is shared with all routes and resources within the same application. When using an http actor, state can be accessed with the HttpRequest::state() as read-only, but interior mutability with RefCell can be used to achieve state mutability. State is also available for route matching predicates and middlewares.




                In this case should be something like:



                extern crate actix_web;

                use actix_web::actix::{Actor, Addr, Context, System};
                use actix_web::{http, server, App, HttpRequest, HttpResponse, Result};
                use std::collections::HashMap;
                use actix_web::dev::Handler;

                #[derive(Clone)]
                pub struct CacheActor {
                caches: HashMap<String, String>,
                }

                impl CacheActor {
                pub fn new() -> Self {
                CacheActor {
                caches: HashMap::new(),
                }
                }
                }

                impl Actor for CacheActor {
                type Context = Context<Self>;
                }

                impl<S> Handler<S> for CacheActor {
                type Result = String;

                fn handle(&self, _req: &HttpRequest<S>) -> Self::Result {
                unimplemented!();
                }
                }

                fn list_resources(req: &HttpRequest<Addr<CacheActor>>) -> Result<HttpResponse> {
                Ok(HttpResponse::Found()
                .header(http::header::LOCATION, format!("hello {}", req.path()))
                .finish())
                }

                fn main() {
                let system = System::new("Example");

                server::new(|| {
                let cache_addr = CacheActor::new().start();
                App::with_state(cache_addr)
                .resource("/world", |r| r.method(http::Method::GET).f(list_resources))
                })
                .bind("127.0.0.1:8080")
                .unwrap()
                .run();

                system.run();
                }





                share|improve this answer













                Look at the App::route signature:



                pub fn route<T, F, R>(self, path: &str, method: Method, f: F) -> App<S> 
                where
                F: WithFactory<T, S, R>,
                R: Responder + 'static,
                T: FromRequest<S> + 'static,


                F generic depends on T and R that in turn have 'static lifetime requirement.



                Your closure captures an &Addr<CacheActor> that it is not valid for 'static lifetime and this generates the error.



                A possibility that I see is to use the App "State", directly from the docs:




                Application state is shared with all routes and resources within the same application. When using an http actor, state can be accessed with the HttpRequest::state() as read-only, but interior mutability with RefCell can be used to achieve state mutability. State is also available for route matching predicates and middlewares.




                In this case should be something like:



                extern crate actix_web;

                use actix_web::actix::{Actor, Addr, Context, System};
                use actix_web::{http, server, App, HttpRequest, HttpResponse, Result};
                use std::collections::HashMap;
                use actix_web::dev::Handler;

                #[derive(Clone)]
                pub struct CacheActor {
                caches: HashMap<String, String>,
                }

                impl CacheActor {
                pub fn new() -> Self {
                CacheActor {
                caches: HashMap::new(),
                }
                }
                }

                impl Actor for CacheActor {
                type Context = Context<Self>;
                }

                impl<S> Handler<S> for CacheActor {
                type Result = String;

                fn handle(&self, _req: &HttpRequest<S>) -> Self::Result {
                unimplemented!();
                }
                }

                fn list_resources(req: &HttpRequest<Addr<CacheActor>>) -> Result<HttpResponse> {
                Ok(HttpResponse::Found()
                .header(http::header::LOCATION, format!("hello {}", req.path()))
                .finish())
                }

                fn main() {
                let system = System::new("Example");

                server::new(|| {
                let cache_addr = CacheActor::new().start();
                App::with_state(cache_addr)
                .resource("/world", |r| r.method(http::Method::GET).f(list_resources))
                })
                .bind("127.0.0.1:8080")
                .unwrap()
                .run();

                system.run();
                }






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 28 '18 at 10:07









                attdonaattdona

                4,07021421




                4,07021421
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53465548%2flifetime-issue-with-actix-web%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    404 Error Contact Form 7 ajax form submitting

                    How to know if a Active Directory user can login interactively

                    TypeError: fit_transform() missing 1 required positional argument: 'X'