nickel-org / nickel.rs

An expressjs inspired web framework for Rust
http://nickel-org.github.io/
MIT License
3.04k stars 157 forks source link

How to use an handler with self ? #446

Closed imclint21 closed 5 years ago

imclint21 commented 5 years ago

Hey,

I try to create a handler in an impl, I get some errors, is it possible?

Cheers

jolhoeft commented 5 years ago

Not sure I understand. Are you trying to impl Middleware in a struct? Do you have some sample code of what you are trying to do?

imclint21 commented 5 years ago

Yes, I just want to implement a Middleware in an impl, like this:

fn router_api(&self) -> nickel::Router {
    let mut router = Nickel::router();

    let m = (self.hello_world)(self);

    router.add_route(Method::Head, "/api/kv/:key", m);
imclint21 commented 5 years ago

Hi, @jolhoeft I've added you on discord!

This is my snippet code, do you have an idea how to do that?

extern crate nickel;

use nickel::{Nickel, HttpRouter, Request, Response, MiddlewareResult};

struct Server;

impl Server {
    fn hello_world<'mw>(&self, _req: &mut Request, res: Response<'mw>) -> MiddlewareResult<'mw> {
        res.send("Hello World")
    }

    fn default()
    {
        let mut server = Nickel::new();
        server.get("**", hello_world); // << how to use hello_world in the current scope
        server.listen("127.0.0.1:6767").unwrap();
    }
}

fn main() {
    Server::default();
}
jolhoeft commented 5 years ago

I think this will work if you remove &self from the hello_world fn. It isn't needed since you are not using it. This will make the function signature match one of the default implementations of the Middleware trait. You may need to refer to it as Server::hello_world.

imclint21 commented 5 years ago

Okey, thank you ^^