carllerche / tower-web

A fast, boilerplate free, web framework for Rust
MIT License
980 stars 51 forks source link

in middleware,how to direct return a response? #156

Closed goodclouddata closed 5 years ago

goodclouddata commented 5 years ago

I wtrite a middleware, to special URL,It should direct return a response,or it return inner Service,But when compiler ,what wrong with it?

//code is here, the key code bettwen //---------

impl<T, B> Future for ResponseFuture where T: Future<Item = http::Response>, T::Error: ::std::error::Error, B: BufStream, { type Item = T::Item; type Error = T::Error;

fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
    use futures::Async::{self, *};

//------------------------------------------------------ let full_path = self.path.as_ref().map(|p| p.as_str()).unwrap_or("/");

    info!("the fulloath is {:?}", full_path);

    if full_path.starts_with("/hello-future") {
        use http::Response;
        let response = Response::new("hello world".to_string());

   // here  compile error 
        return Ok(Ready(response));

//----------------------------------------------------- }

    let res = self.inner.poll();

    match res {
        Ok(Ready(ref response)) => {
            // TODO:
            // - remote_addr
            // - response content length
            // - date
            info!(
                target: self.target,
                "\"{} {} {:?}\" {} {:?}",
                self.method,
                full_path,
                self.version,
                response.status().as_u16(),
                self.start.elapsed(),
            );
        }
        Err(ref err) => {
            warn!("ERROR: {}", err);
        }
        _ => {}
    }

    res
}

}

//eror is here

error[E0308]: mismatched types
--> src/logic/interceptor.rs:86:29
86 return Ok(Ready(response)); ^^^^^^^^ expected type parameter, found struct std::string::String

= note: expected type http::Response<B>
found type http::Response<std::string::String>

error: aborting due to previous error

carllerche commented 5 years ago

http::Response<T> is generic over the body type. It looks like the inner future's response body type is not String, yet you are trying to return String.

You can either map String to the same type as the inner future's body type or your future can have a body type of Either<InnerResponseBody, String>. (Either)

Hope this helps!

goodclouddata commented 5 years ago

Ok.I'll try.Thanks!