Skip to content

Instantly share code, notes, and snippets.

@bradleybeddoes
Created March 5, 2018 10:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradleybeddoes/c2c740014a64a4efae00ac25a5ffccca to your computer and use it in GitHub Desktop.
Save bradleybeddoes/c2c740014a64a4efae00ac25a5ffccca to your computer and use it in GitHub Desktop.
Impl NewHandler for struct with members
extern crate gotham;
extern crate hyper;
extern crate futures;
use std::io;
use hyper::{Response, StatusCode};
use futures::future;
use gotham::handler::{Handler, HandlerFuture, NewHandler};
use gotham::state::State;
use gotham::router::Router;
use gotham::router::builder::*;
use gotham::pipeline::new_pipeline;
use gotham::pipeline::single::*;
use gotham::middleware::session::NewSessionMiddleware;
use gotham::test::TestServer;
struct MyNewHandler {
x: u8
}
struct MyHandler {
y: u8
}
impl MyNewHandler {
pub fn new(x: u8) -> MyNewHandler {
Self { x }
}
}
impl NewHandler for MyNewHandler {
type Instance = MyHandler;
fn new_handler(&self) -> io::Result<Self::Instance> {
Ok(MyHandler::new(self.x))
}
}
impl MyHandler {
pub fn new(y: u8) -> Self {
Self { y }
}
}
impl Handler for MyHandler {
fn handle(self, state: State) -> Box<HandlerFuture> {
println!("y: {}", self.y);
// Handler implementation elided.
let response = Response::new().with_status(StatusCode::Accepted);
Box::new(future::ok((state, response)))
}
}
fn router() -> Router {
let (chain, pipelines) = single_pipeline(
new_pipeline().add(NewSessionMiddleware::default()).build()
);
build_router(chain, pipelines, |route| {
route.get("/").to_new_handler(MyNewHandler::new(0));
})
}
fn main() {
let test_server = TestServer::new(router()).unwrap();
let response = test_server.client()
.get("https://example.com/request/path")
.perform()
.unwrap();
assert_eq!(response.status(), StatusCode::Accepted);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment