Skip to content

Commit

Permalink
fix(examples): Fix examples triggering issue nickel-org#399
Browse files Browse the repository at this point in the history
Fix the examples that were returning MiddlewareResults in the
middlware! macro. A couple could be changed to return a Responder, but
most needed to be reimplemented as seperate functions.

Updated the middleware! macro documentaion to note the limitations
from issues nickel-org#399 and nickel-org#389.

Disable ssl testing in travis, which was broken in commit
8d5a7d0. Issue nickel-org#415 to track
our SSL plan.
  • Loading branch information
jolhoeft committed Nov 23, 2017
1 parent dc55b3d commit 433a599
Show file tree
Hide file tree
Showing 15 changed files with 78 additions and 54 deletions.
1 change: 0 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,5 +38,4 @@ env:
global:
secure: nPXTdkq9TK4LmqJWqB4jxscDG1mnqJzO0UX5ni+oC0SohjgBxdWjbvJ8Kthk3c8Qg/2zGlCryuT1lV4TcD3jF86MHlRlXsO3G8fCbEGdLLzppbV0A2VnEw1knhv2mfUhxA8hsFJE2ncT5qeOVyQ6N3PAMGoYkdhhbD9N/9EWuqs=
matrix:
- FEATURES="--features ssl"
- FEATURES=""
42 changes: 23 additions & 19 deletions examples/form_data/form_data.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,34 @@
#[macro_use] extern crate nickel;
use nickel::{Nickel, HttpRouter, FormBody};
use nickel::{Nickel, HttpRouter, FormBody, Request, Response, MiddlewareResult};
use std::collections::HashMap;

fn main() {
let mut server = Nickel::new();
fn root<'mw, 'conn>(_req: &mut Request<'mw, 'conn>, res: Response<'mw>) -> MiddlewareResult<'mw> {
let mut data = HashMap::new();
data.insert("title","Contact");

return res.render("examples/form_data/views/contact.html", &data)
}

server.get("/", middleware! { |_, res|
let mut data = HashMap::new();
data.insert("title","Contact");
fn confirmation<'mw, 'conn>(req: &mut Request<'mw, 'conn>, res: Response<'mw>) -> MiddlewareResult<'mw> {
let form_data = try_with!(res, req.form_body());

return res.render("examples/form_data/views/contact.html", &data)
});
println!("{:?}", form_data);

server.post("/confirmation", middleware!{ |req, res|
let form_data = try_with!(res, req.form_body());
let mut data = HashMap::new();
data.insert("title", "Confirmation");
data.insert("firstname", form_data.get("firstname").unwrap_or("First name?"));
data.insert("lastname", form_data.get("lastname").unwrap_or("Last name?"));
data.insert("phone", form_data.get("phone").unwrap_or("Phone?"));
data.insert("email", form_data.get("email").unwrap_or("Email?"));
return res.render("examples/form_data/views/confirmation.html", &data)
}

fn main() {
let mut server = Nickel::new();

println!("{:?}", form_data);
server.get("/", root);

let mut data = HashMap::new();
data.insert("title", "Confirmation");
data.insert("firstname", form_data.get("firstname").unwrap_or("First name?"));
data.insert("lastname", form_data.get("lastname").unwrap_or("Last name?"));
data.insert("phone", form_data.get("phone").unwrap_or("Phone?"));
data.insert("email", form_data.get("email").unwrap_or("Email?"));
return res.render("examples/form_data/views/confirmation.html", &data)
});
server.post("/confirmation", confirmation);

server.listen("0.0.0.0:8080").unwrap();
}
2 changes: 1 addition & 1 deletion examples/hello_world.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#[macro_use] extern crate nickel;
extern crate nickel;

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

Expand Down
12 changes: 7 additions & 5 deletions examples/integration_testing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ extern crate nickel;
extern crate hyper;
extern crate rustc_serialize;

use nickel::{Nickel, ListeningServer, HttpRouter, JsonBody};
use nickel::{Nickel, ListeningServer, HttpRouter, JsonBody, Request, Response, MiddlewareResult};
use nickel::status::StatusCode;

use rustc_serialize::json::Json;
Expand Down Expand Up @@ -60,6 +60,11 @@ fn main() {
start_server(address, database).unwrap();
}

fn log_hit<'mw, 'conn>(_req: &mut Request<'mw, 'conn, ServerData>, res: Response<'mw, ServerData>) -> MiddlewareResult<'mw, ServerData> {
res.data().log_hit();
return res.next_middleware()
}

fn start_server<D>(address: &str, database: D) -> Result<ListeningServer, Box<StdError>>
where D: Database {
let server_data = ServerData {
Expand All @@ -70,10 +75,7 @@ where D: Database {
let mut server = Nickel::with_data(server_data);

// Track all hits to the server
server.utilize(middleware! { |_req, res| <ServerData>
res.data().log_hit();
return res.next_middleware()
});
server.utilize(log_hit);

// Core server
server.get("/", middleware!( "Hello World" ));
Expand Down
2 changes: 1 addition & 1 deletion examples/macro_example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::io::Write;
use nickel::status::StatusCode::{self, NotFound};
use nickel::{
Nickel, NickelError, Continue, Halt, Request, Response, MediaType,
QueryString, JsonBody, StaticFilesHandler, MiddlewareResult, HttpRouter, Action
QueryString, JsonBody, StaticFilesHandler, MiddlewareResult, Action
};
use regex::Regex;
use hyper::header::Location;
Expand Down
4 changes: 2 additions & 2 deletions examples/no_macro_custom_data.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#[macro_use] extern crate nickel;
extern crate nickel;

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

Expand All @@ -16,5 +16,5 @@ fn main() {

let mut server = Nickel::with_data(my_config);
server.get("**", greeter);
server.listen("127.0.0.1:6767");
server.listen("127.0.0.1:6767").unwrap();
}
2 changes: 1 addition & 1 deletion examples/static_files.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#[macro_use] extern crate nickel;
extern crate nickel;

use nickel::{Nickel, StaticFilesHandler};

Expand Down
18 changes: 9 additions & 9 deletions examples/template.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
#[macro_use] extern crate nickel;
extern crate nickel;

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

fn render<'mw, 'conn>(_req: &mut Request<'mw, 'conn>, res: Response<'mw>) -> MiddlewareResult<'mw> {
let mut data = HashMap::<&str, &str>::new();
data.insert("name", "user");
return res.render("examples/assets/template.tpl", &data)
}

fn main() {
let mut server = Nickel::new();

// * NOTE *
// This example is deprecated, you should use nickel_mustache from crates.io
server.get("/", middleware! { |_, res|
let mut data = HashMap::<&str, &str>::new();
data.insert("name", "user");
return res.render("examples/assets/template.tpl", &data)
});
server.get("/", render);

server.listen("127.0.0.1:6767").unwrap();
}
2 changes: 1 addition & 1 deletion src/body_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ pub trait FormBody {
/// let mut server = Nickel::new();
/// server.post("/a", middleware! { |req, res|
/// let form_body = try_with!(res, req.form_body());
/// return res.send(format!("Post: {:?}", form_body))
/// format!("Post: {:?}", form_body)
/// });
/// }
/// ```
Expand Down
14 changes: 8 additions & 6 deletions src/extensions/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,19 @@ impl<'mw, 'server, D> Referer for Request<'mw, 'server, D> {
///
/// # Examples
/// ```{rust}
/// #[macro_use] extern crate nickel;
/// extern crate nickel;
///
/// use nickel::{Nickel, HttpRouter};
/// use nickel::{Nickel, HttpRouter, Request, Response, MiddlewareResult};
/// use nickel::extensions::{Referer, Redirect};
///
/// fn referer<'mw, 'conn>(req: &mut Request<'mw, 'conn>, res: Response<'mw>) -> MiddlewareResult<'mw> {
/// let back = req.referer().unwrap_or("http://nickel-org.github.io/");
/// return res.redirect(back)
/// }
///
/// fn main() {
/// let mut server = Nickel::new();
/// server.get("/a", middleware! { |req, res|
/// let back = req.referer().unwrap_or("http://nickel.rs");
/// return res.redirect(back)
/// });
/// server.get("/a", referer);
/// }
/// ```
fn referer(&self) -> Option<&str> {
Expand Down
14 changes: 9 additions & 5 deletions src/extensions/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,18 @@ pub trait Redirect: Sized {
///
/// # Examples
/// ```{rust}
/// #[macro_use] extern crate nickel;
/// extern crate nickel;
///
/// use nickel::{Nickel, HttpRouter};
/// use nickel::{Nickel, HttpRouter, Request, Response, MiddlewareResult};
/// use nickel::extensions::Redirect;
///
/// fn redirect<'mw, 'conn>(_: &mut Request<'mw, 'conn>, res: Response<'mw>) -> MiddlewareResult<'mw> {
/// return res.redirect("http://nickel.rs")
/// }
///
/// fn main() {
/// let mut server = Nickel::new();
/// server.get("/a", middleware! { |_, res|
/// return res.redirect("http://nickel.rs")
/// });
/// server.get("/a", redirect);
/// }
/// ```
fn redirect<T>(self, target: T) -> Self::Result
Expand All @@ -35,6 +37,8 @@ pub trait Redirect: Sized {
where T: Into<String>;
}

// Todo: rework this to return a Responder so it will work with the
// middleware macro
impl<'a, D> Redirect for Response<'a, D> {
type Result = MiddlewareResult<'a, D>;

Expand Down
13 changes: 13 additions & 0 deletions src/macros/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,19 @@
/// In future, the macro should hopefully be able to be removed while
/// having minimal changes to the closure's code.
///
/// # Limitations
///
/// The body of the `middleware!` macro needs to return something
/// implementing `Responder`. Some older examples had bodies that
/// would return a `MiddlewareResult`, but this was exploiting an
/// unsoundness in the Rust compiler that has since been
/// tightened. See discussion at
/// https://github.com/nickel-org/nickel.rs/issues/399.
///
/// Due to the way the macro is expanded, exiting the body early with
/// a return statement will most likely fail with a cryptic error
/// message. See https://github.com/nickel-org/nickel.rs/issues/389.
///
/// # Examples
/// ```rust,no_run
/// # #[macro_use] extern crate nickel;
Expand Down
2 changes: 1 addition & 1 deletion src/query_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub trait QueryString {
/// let mut server = Nickel::new();
/// server.get("/a", middleware! { |req, res|
/// let query = req.query();
/// return res.send(format!("Query: {:?}", query))
/// format!("Query: {:?}", query)
/// });
/// }
/// ```
Expand Down
2 changes: 1 addition & 1 deletion src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use time;
use mimes::MediaType;
use mustache;
use mustache::Template;
use std::io::{self, Read, Write, copy};
use std::io::{self, Write, copy};
use std::fs::File;
use std::any::Any;
use {NickelError, Halt, MiddlewareResult, Responder, Action};
Expand Down
2 changes: 1 addition & 1 deletion src/urlencoded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use groupable::Groupable;
use hyper::uri::RequestUri;
use hyper::uri::RequestUri::{Star, AbsoluteUri, AbsolutePath, Authority};
use std::collections::HashMap;
use url::{form_urlencoded, Url};
use url::form_urlencoded;

type QueryStore = HashMap<String, Vec<String>>;

Expand Down

0 comments on commit 433a599

Please sign in to comment.