nickel-org / nickel.rs

An expressjs inspired web framework for Rust

Home Page:http://nickel-org.github.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to use an handler with self ?

imclint21 opened this issue · comments

Hey,

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

Cheers

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?

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);

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();
}

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.

Okey, thank you ^^