Ogeon / rustful

[OUTDATED] A light HTTP framework for Rust
https://docs.rs/rustful
Apache License 2.0
862 stars 51 forks source link

How does a function return a "router" #132

Closed greenpdx closed 7 years ago

greenpdx commented 7 years ago

I want a function to return a router to main()

the problem is I return a method_router::Build and when I change my return to Build then I get lifetime issues.

pub fn build_router() -> MethodRouter { // let mut router = DefaultRouter::Api::new(); let mut router = MethodRouter::::new(); // let mut router = MethodRouter::default(); //Global actions let router = router.build().many(|mut endpoint| { endpoint.on_get(Api(Some(tnv_get))); endpoint.on_post(Api(Some(tnv_post))); endpoint.on_options(Api(Some(tnv_get))); }); router }

Ogeon commented 7 years ago

Nice to see that you are trying out the new API. Any feedback is welcome!

A you have notices, build and many and some of the other methods return a &mut Builder<'a, T>. This builder is tied to your router variable (the original one), since it contains a reference to it, and can't leave the function. Its only purpose is for method chaining.

What you want to return is that original router variable, which has been modified to contain your routes:

pub fn build_router() -> MethodRouter<Api> {
    let mut router = MethodRouter::<Api>::new();

    // Notice how I just removed the `let router = ...` part
    router.build().many(|mut endpoint| {
        endpoint.on_get(Api(Some(tnv_get)));
        endpoint.on_post(Api(Some(tnv_post)));
        endpoint.on_options(Api(Some(tnv_get)));
    });

    // Return the original router, now with the handlers inside
    router
}

I don't know if you had Api in MethodRouter<Api>, so you have to adjust it to your needs. If you format your code examples like this:

```rust code here ```

You should get proper code blocks with nice coloring, and Type<Parameters> should not disappear. :slightly_smiling_face:

greenpdx commented 7 years ago

Thanks that worked.