Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve AroundMiddleware API #569

Open
jethrogb opened this issue Dec 1, 2017 · 0 comments
Open

Improve AroundMiddleware API #569

jethrogb opened this issue Dec 1, 2017 · 0 comments

Comments

@jethrogb
Copy link

jethrogb commented Dec 1, 2017

Types that implement the BeforeMiddleware or AfterMiddleware traits are the actual middleware handler. However, types that implements AroundMiddleware are more like builders, and another type is going to be the actual middleware handler. This seems rather unnecessary and confusing to me.

I think a better design for the AroundMiddleware API would be:

trait AroundMiddleware {
    fn around(&self, _: &mut Request, _: &Handler) -> IronResult<Response>;
}

Here's a preliminary implementation:

trait AroundMiddleware: Send + Sync + 'static {
    fn around(&self, _: &mut Request, _: &Handler) -> IronResult<Response>;
}

struct AroundNode {
    cur: Box<AroundMiddleware>,
    next: Option<Arc<AroundNode>>
}

struct Chain {
    arounds: Option<Arc<AroundNode>>,
    main: Arc<Handler>
}

impl Chain {
    fn handle(&self, req: &mut Request) -> IronResult<Response> {
        impl Handler for (Option<Arc<AroundNode>>, Arc<Handler>) {
            fn handle(&self, req: &mut Request) -> IronResult<Response> {
                if let Some(ref node) = self.0 {
                    node.cur.around(req, &(node.next.clone(), self.1.clone()))
                } else {
                    self.1.handle(req)
                }
            }
        }

        // before middleware

        (self.arounds.clone(), self.main.clone()).handle(req)

        // after middleware
    }

    fn link_around<A: AroundMiddleware>(&mut self, around: A) {
        let cur = Box::new(around);
        let next = self.arounds.take();
        self.arounds = Some(Arc::new(AroundNode{cur,next}));
    }
}

Arcs are needed because of the 'static bounds. Otherwise, could've used references. Happy to turn this into a PR if you think this is a good idea.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants