Skip to content

Commit

Permalink
Merge pull request #176 from rawler/code-cleanup
Browse files Browse the repository at this point in the history
Code cleanup
  • Loading branch information
rawler committed Aug 31, 2020
2 parents 5e4fe04 + 59fc12e commit fa5b19b
Show file tree
Hide file tree
Showing 23 changed files with 856 additions and 559 deletions.
10 changes: 7 additions & 3 deletions benches/bench.rs
Expand Up @@ -22,7 +22,7 @@ fn curl_bench() {
.output()
{
Ok(p) => p,
Err(_) => return, // ignoring test
Err(_) => return, // ignoring test
};

drop(server);
Expand Down Expand Up @@ -58,14 +58,18 @@ fn parallel_requests(bencher: &mut test::Bencher) {

for _ in 0..1000usize {
let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
(write!(stream, "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")).unwrap();
(write!(
stream,
"GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"
))
.unwrap();
streams.push(stream);
}

loop {
let request = match server.try_recv().unwrap() {
None => break,
Some(rq) => rq
Some(rq) => rq,
};

assert_eq!(request.method(), &Method::Get);
Expand Down
2 changes: 1 addition & 1 deletion examples/hello-world.rs
Expand Up @@ -9,7 +9,7 @@ fn main() {

let mut handles = Vec::new();

for _ in 0 .. 4 {
for _ in 0..4 {
let server = server.clone();

handles.push(thread::spawn(move || {
Expand Down
26 changes: 17 additions & 9 deletions examples/php-cgi.rs
Expand Up @@ -12,15 +12,18 @@ Usage: php-cgi <php-script-path>
*/

fn handle(rq: tiny_http::Request, script: &str) {
use std::process::Command;
use std::io::Write;
use std::process::Command;

let php = Command::new("php-cgi")
.arg(script)
//.stdin(Ignored)
//.extra_io(Ignored)
.env("AUTH_TYPE", "")
.env("CONTENT_LENGTH", format!("{}", rq.body_length().unwrap_or(0)))
.env(
"CONTENT_LENGTH",
format!("{}", rq.body_length().unwrap_or(0)),
)
.env("CONTENT_TYPE", "")
.env("GATEWAY_INTERFACE", "CGI/1.1")
.env("PATH_INFO", "")
Expand All @@ -39,41 +42,46 @@ fn handle(rq: tiny_http::Request, script: &str) {
.output()
.unwrap();


// note: this is not a good implementation
// cgi returns the status code in the headers ; also many headers will be missing
// in the response
match php.status {
status if status.success() => {
let mut writer = rq.into_writer();
let mut writer: &mut Write = &mut *writer;
let writer: &mut dyn Write = &mut *writer;

(write!(writer, "HTTP/1.1 200 OK\r\n")).unwrap();
(write!(writer, "{}", php.stdout.clone().as_ascii_str().unwrap())).unwrap();

writer.flush().unwrap();
},
}
_ => {
println!("Error in script execution: {}", php.stderr.clone().as_ascii_str().unwrap());
println!(
"Error in script execution: {}",
php.stderr.clone().as_ascii_str().unwrap()
);
}
}
}

fn main() {
use std::env;
use std::sync::Arc;
use std::thread::spawn;
use std::env;

let php_script = {
let mut args = env::args();
if args.len() < 2 { println!("Usage: php-cgi <php-script-path>"); return }
if args.len() < 2 {
println!("Usage: php-cgi <php-script-path>");
return;
}
args.nth(1).unwrap()
};

let server = Arc::new(tiny_http::Server::http("0.0.0.0:9975").unwrap());
println!("Now listening on port 9975");

let num_cpus = 4; // TODO: dynamically generate this value
let num_cpus = 4; // TODO: dynamically generate this value
for _ in 0..num_cpus {
let server = server.clone();
let php_script = php_script.clone();
Expand Down
7 changes: 4 additions & 3 deletions examples/readme-example.rs
@@ -1,18 +1,19 @@
extern crate tiny_http;

fn main() {
use tiny_http::{Server, Response};
use tiny_http::{Response, Server};

let server = Server::http("0.0.0.0:8000").unwrap();

for request in server.incoming_requests() {
println!("received request! method: {:?}, url: {:?}, headers: {:?}",
println!(
"received request! method: {:?}, url: {:?}, headers: {:?}",
request.method(),
request.url(),
request.headers()
);

let response = Response::from_string("hello world");
request.respond(response);
request.respond(response).expect("Responded");
}
}
21 changes: 9 additions & 12 deletions examples/serve-root.rs
@@ -1,14 +1,14 @@
use std::path::Path;
use std::fs;
use ascii::AsciiString;
use std::fs;
use std::path::Path;

extern crate ascii;
extern crate tiny_http;

fn get_content_type(path: &Path) -> &'static str {
let extension = match path.extension() {
None => return "text/plain",
Some(e) => e
Some(e) => e,
};

match extension.to_str().unwrap() {
Expand All @@ -20,7 +20,7 @@ fn get_content_type(path: &Path) -> &'static str {
"htm" => "text/html; charset=utf8",
"html" => "text/html; charset=utf8",
"txt" => "text/plain; charset=utf8",
_ => "text/plain; charset=utf8"
_ => "text/plain; charset=utf8",
}
}

Expand All @@ -32,7 +32,7 @@ fn main() {
loop {
let rq = match server.recv() {
Ok(rq) => rq,
Err(_) => break
Err(_) => break,
};

println!("{:?}", rq);
Expand All @@ -44,15 +44,12 @@ fn main() {
if file.is_ok() {
let response = tiny_http::Response::from_file(file.unwrap());

let response = response.with_header(
tiny_http::Header {
field: "Content-Type".parse().unwrap(),
value: AsciiString::from_ascii(get_content_type(&path)).unwrap(),
}
);
let response = response.with_header(tiny_http::Header {
field: "Content-Type".parse().unwrap(),
value: AsciiString::from_ascii(get_content_type(&path)).unwrap(),
});

let _ = rq.respond(response);

} else {
let rep = tiny_http::Response::new_empty(tiny_http::StatusCode(404));
let _ = rq.respond(rep);
Expand Down
27 changes: 18 additions & 9 deletions examples/ssl.rs
@@ -1,25 +1,34 @@
extern crate tiny_http;

#[cfg(not(feature = "ssl"))]
fn main() { println!("This example requires the `ssl` feature to be enabled"); }
fn main() {
println!("This example requires the `ssl` feature to be enabled");
}

#[cfg(feature = "ssl")]
fn main() {
use tiny_http::{Server, Response};
use tiny_http::{Response, Server};

let server = Server::https("0.0.0.0:8000", tiny_http::SslConfig {
certificate: include_bytes!("ssl-cert.pem").to_vec(),
private_key: include_bytes!("ssl-key.pem").to_vec(),
}).unwrap();
let server = Server::https(
"0.0.0.0:8000",
tiny_http::SslConfig {
certificate: include_bytes!("ssl-cert.pem").to_vec(),
private_key: include_bytes!("ssl-key.pem").to_vec(),
},
)
.unwrap();

println!("Note: connecting to this server will likely give you a warning from your browser \
println!(
"Note: connecting to this server will likely give you a warning from your browser \
because the connection is unsecure. This is because the certificate used by this \
example is self-signed. With a real certificate, you wouldn't get this warning.");
example is self-signed. With a real certificate, you wouldn't get this warning."
);

for request in server.incoming_requests() {
assert!(request.secure());

println!("received request! method: {:?}, url: {:?}, headers: {:?}",
println!(
"received request! method: {:?}, url: {:?}, headers: {:?}",
request.method(),
request.url(),
request.headers()
Expand Down

0 comments on commit fa5b19b

Please sign in to comment.