2016-09-04 20:51:16 +00:00
|
|
|
#![feature(plugin)]
|
2016-09-09 03:38:58 +00:00
|
|
|
#![plugin(rocket_codegen)]
|
2016-09-04 20:51:16 +00:00
|
|
|
|
|
|
|
extern crate rocket;
|
|
|
|
|
|
|
|
use std::fmt;
|
2016-10-25 09:17:49 +00:00
|
|
|
use rocket::request::{self, Request, FromRequest};
|
|
|
|
use rocket::outcome::Outcome::*;
|
2016-09-04 20:51:16 +00:00
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
struct HeaderCount(usize);
|
|
|
|
|
|
|
|
impl fmt::Display for HeaderCount {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
write!(f, "{}", self.0)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-16 11:07:23 +00:00
|
|
|
impl<'a, 'r> FromRequest<'a, 'r> for HeaderCount {
|
2016-09-04 20:51:16 +00:00
|
|
|
type Error = ();
|
2016-12-16 11:07:23 +00:00
|
|
|
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, ()> {
|
2016-10-25 09:17:49 +00:00
|
|
|
Success(HeaderCount(request.headers().len()))
|
2016-09-04 20:51:16 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[get("/")]
|
|
|
|
fn header_count(header_count: HeaderCount) -> String {
|
|
|
|
format!("Your request contained {} headers!", header_count)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2017-03-16 05:10:09 +00:00
|
|
|
rocket::ignite().mount("/", routes![header_count]).launch();
|
2016-09-04 20:51:16 +00:00
|
|
|
}
|
2016-10-16 10:16:16 +00:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
|
|
|
use super::rocket;
|
|
|
|
use rocket::testing::MockRequest;
|
|
|
|
use rocket::http::Method::*;
|
2016-12-16 00:34:19 +00:00
|
|
|
use rocket::http::Header;
|
|
|
|
|
|
|
|
fn test_header_count<'h>(headers: Vec<Header<'static>>) {
|
2017-01-21 03:31:46 +00:00
|
|
|
let rocket = rocket::ignite()
|
|
|
|
.mount("/", routes![super::header_count]);
|
|
|
|
|
2016-12-16 00:34:19 +00:00
|
|
|
let mut req = MockRequest::new(Get, "/");
|
2017-01-31 10:43:19 +00:00
|
|
|
for header in headers.iter().cloned() {
|
2016-12-16 00:34:19 +00:00
|
|
|
req = req.header(header);
|
|
|
|
}
|
2016-10-16 10:16:16 +00:00
|
|
|
|
2016-12-16 04:53:54 +00:00
|
|
|
let mut response = req.dispatch_with(&rocket);
|
2017-01-31 10:43:19 +00:00
|
|
|
let expect = format!("Your request contained {} headers!", headers.len());
|
2017-04-14 08:59:28 +00:00
|
|
|
assert_eq!(response.body_string(), Some(expect));
|
2016-10-16 10:16:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_n_headers() {
|
|
|
|
for i in 0..50 {
|
2017-01-31 10:43:19 +00:00
|
|
|
let headers = (0..i).map(|n| Header::new(n.to_string(), n.to_string()))
|
|
|
|
.collect();
|
2016-10-16 10:16:16 +00:00
|
|
|
|
2016-12-16 00:34:19 +00:00
|
|
|
test_header_count(headers);
|
2016-10-16 10:16:16 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|