Created
April 11, 2017 12:26
-
-
Save solebox/4432899d4bed3e2e549099fbea01691b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(plugin)] | |
#![plugin(rocket_codegen)] | |
extern crate rocket; | |
use std::fmt; | |
use rocket::request::{self, Request, FromRequest}; | |
use rocket::outcome::Outcome::*; | |
#[derive(Debug)] | |
struct HeaderCount<'r>{ | |
headers: rocket::http::HeaderMap<'r>, | |
} | |
impl<'r> fmt::Display for HeaderCount<'r> { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
let mut s1 = "".to_string(); | |
for key in self.headers.iter() { | |
s1.push_str(key.value()); | |
s1.push_str(":"); | |
s1.push_str(key.name()); | |
s1.push_str("\n"); | |
} | |
write!(f, "{}", s1)//self.0) | |
} | |
} | |
impl<'a, 'r> FromRequest<'a, 'r> for HeaderCount<'r> { | |
type Error = (); | |
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, ()> { | |
Success(HeaderCount { headers: request.headers().clone() }) | |
} | |
} | |
#[get("/")] | |
fn header_count(header_count: HeaderCount) -> String { | |
// return the headers to the user | |
format!("{}", header_count) | |
} | |
fn main() { | |
rocket::ignite().mount("/", routes![header_count]).launch(); | |
} | |
#[cfg(test)] | |
mod test { | |
use super::rocket; | |
use rocket::testing::MockRequest; | |
use rocket::http::Method::*; | |
use rocket::http::Header; | |
fn test_header_count<'h>(headers: Vec<Header<'static>>) { | |
let rocket = rocket::ignite() | |
.mount("/", routes![super::header_count]); | |
let mut req = MockRequest::new(Get, "/"); | |
for header in headers.iter().cloned() { | |
req = req.header(header); | |
} | |
let mut response = req.dispatch_with(&rocket); | |
let expect = format!("Your request contained {} headers!", headers.len()); | |
assert_eq!(response.body().and_then(|b| b.into_string()), Some(expect)); | |
} | |
#[test] | |
fn test_n_headers() { | |
for i in 0..50 { | |
let headers = (0..i).map(|n| Header::new(n.to_string(), n.to_string())) | |
.collect(); | |
test_header_count(headers); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment