chore(lib): individually disable tests and examples that aren't updated

This commit is contained in:
Sean McArthur
2019-07-12 13:29:57 -07:00
parent f93463b3d9
commit 5da17df97f
29 changed files with 120 additions and 61 deletions

View File

@@ -1,7 +1,5 @@
#![feature(async_await)]
#![deny(warnings)]
extern crate hyper;
//#![deny(warnings)]
use hyper::{Body, Method, Request, Response, Server, StatusCode};
use hyper::service::{make_service_fn, service_fn};

View File

@@ -1,44 +0,0 @@
#![deny(warnings)]
extern crate hyper;
extern crate pretty_env_logger;
use hyper::{Client, Server};
use hyper::service::service_fn;
use hyper::rt::{self, Future};
use std::net::SocketAddr;
fn main() {
pretty_env_logger::init();
let in_addr = ([127, 0, 0, 1], 3001).into();
let out_addr: SocketAddr = ([127, 0, 0, 1], 3000).into();
let client_main = Client::new();
let out_addr_clone = out_addr.clone();
// new_service is run for each connection, creating a 'service'
// to handle requests for that specific connection.
let new_service = move || {
let client = client_main.clone();
// This is the `Service` that will handle the connection.
// `service_fn_ok` is a helper to convert a function that
// returns a Response into a `Service`.
service_fn(move |mut req| {
let uri_string = format!("http://{}/{}",
out_addr_clone,
req.uri().path_and_query().map(|x| x.as_str()).unwrap_or(""));
let uri = uri_string.parse().unwrap();
*req.uri_mut() = uri;
client.request(req)
})
};
let server = Server::bind(&in_addr)
.serve(new_service)
.map_err(|e| eprintln!("server error: {}", e));
println!("Listening on http://{}", in_addr);
println!("Proxying on http://{}", out_addr);
rt::run(server);
}

View File

@@ -1,79 +0,0 @@
#![deny(warnings)]
extern crate futures;
extern crate hyper;
extern crate pretty_env_logger;
extern crate tokio_fs;
extern crate tokio_io;
use futures::{future, Future};
use hyper::{Body, Method, Request, Response, Server, StatusCode};
use hyper::service::service_fn;
use std::io;
static NOTFOUND: &[u8] = b"Not Found";
static INDEX: &str = "examples/send_file_index.html";
fn main() {
pretty_env_logger::init();
let addr = "127.0.0.1:1337".parse().unwrap();
let server = Server::bind(&addr)
.serve(|| service_fn(response_examples))
.map_err(|e| eprintln!("server error: {}", e));
println!("Listening on http://{}", addr);
hyper::rt::run(server);
}
type ResponseFuture = Box<dyn Future<Item=Response<Body>, Error=io::Error> + Send>;
fn response_examples(req: Request<Body>) -> ResponseFuture {
match (req.method(), req.uri().path()) {
(&Method::GET, "/") | (&Method::GET, "/index.html") | (&Method::GET, "/big_file.html") => {
simple_file_send(INDEX)
},
(&Method::GET, "/no_file.html") => {
// Test what happens when file cannot be be found
simple_file_send("this_file_should_not_exist.html")
},
_ => {
Box::new(future::ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::empty())
.unwrap()))
}
}
}
fn simple_file_send(f: &str) -> ResponseFuture {
// Serve a file by asynchronously reading it entirely into memory.
// Uses tokio_fs to open file asynchronously, then tokio_io to read into
// memory asynchronously.
let filename = f.to_string(); // we need to copy for lifetime issues
Box::new(tokio_fs::file::File::open(filename)
.and_then(|file| {
let buf: Vec<u8> = Vec::new();
tokio_io::io::read_to_end(file, buf)
.and_then(|item| {
Ok(Response::new(item.1.into()))
})
.or_else(|_| {
Ok(Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Body::empty())
.unwrap())
})
})
.or_else(|_| {
Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(NOTFOUND.into())
.unwrap())
}))
}

View File

@@ -1,11 +0,0 @@
<html>
<head>
<title>Hyper responding example</title>
</head>
<body>
<h1>Hyper responding example</h1>
<a href="index.html">index.html</a> Top Level<br>
<a href="big_file.html">big_file.html</a> This page, streamed in chunks<br>
<a href="no_file.html">no_file.html</a> A 404 test, the requested file does not exist<br>
</body>
</html>

View File

@@ -1,51 +0,0 @@
#![deny(warnings)]
extern crate futures;
extern crate hyper;
extern crate pretty_env_logger;
extern crate tokio;
use std::cell::Cell;
use std::rc::Rc;
use hyper::{Body, Response, Server};
use hyper::service::service_fn_ok;
use hyper::rt::Future;
use tokio::runtime::current_thread;
fn main() {
pretty_env_logger::init();
let addr = ([127, 0, 0, 1], 3000).into();
// Using a !Send request counter is fine on 1 thread...
let counter = Rc::new(Cell::new(0));
let new_service = move || {
// For each connection, clone the counter to use in our service...
let cnt = counter.clone();
service_fn_ok(move |_| {
let prev = cnt.get();
cnt.set(prev + 1);
Response::new(Body::from(format!("Request count: {}", prev + 1)))
})
};
// Since the Server needs to spawn some background tasks, we needed
// to configure an Executor that can spawn !Send futures...
let exec = current_thread::TaskExecutor::current();
let server = Server::bind(&addr)
.executor(exec)
.serve(new_service)
.map_err(|e| eprintln!("server error: {}", e));
println!("Listening on http://{}", addr);
current_thread::Runtime::new()
.expect("rt new")
.spawn(server)
.run()
.expect("rt run");
}

View File

@@ -1,55 +0,0 @@
#![deny(warnings)]
extern crate hyper;
extern crate pretty_env_logger;
extern crate serde_json;
use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
use hyper::{Body, Response, Server};
use hyper::service::service_fn_ok;
use hyper::rt::{self, Future};
fn main() {
pretty_env_logger::init();
let addr = ([127, 0, 0, 1], 3000).into();
// For the most basic of state, we just share a counter, that increments
// with each request, and we send its value back in the response.
let counter = Arc::new(AtomicUsize::new(0));
// new_service is run for each connection, creating a 'service'
// to handle requests for that specific connection.
let new_service = move || {
// While the state was moved into the new_service closure,
// we need to clone it here because this closure is called
// once for every connection.
//
// Each connection could send multiple requests, so
// the `Service` needs a clone to handle later requests.
let counter = counter.clone();
// This is the `Service` that will handle the connection.
// `service_fn_ok` is a helper to convert a function that
// returns a Response into a `Service`.
//
// If you wanted to return a `Future` of a `Response`, such as because
// you wish to load data from a database or do other things, you
// could change this to `service_fn` instead.
service_fn_ok(move |_req| {
// Get the current count, and also increment by 1, in a single
// atomic operation.
let count = counter.fetch_add(1, Ordering::AcqRel);
Response::new(Body::from(format!("Request #{}", count)))
})
};
let server = Server::bind(&addr)
.serve(new_service)
.map_err(|e| eprintln!("server error: {}", e));
println!("Listening on http://{}", addr);
rt::run(server);
}

View File

@@ -1,127 +0,0 @@
// Note: `hyper::upgrade` docs link to this upgrade.
extern crate futures;
extern crate hyper;
extern crate tokio;
use std::str;
use futures::sync::oneshot;
use hyper::{Body, Client, Request, Response, Server, StatusCode};
use hyper::header::{UPGRADE, HeaderValue};
use hyper::rt::{self, Future};
use hyper::service::service_fn_ok;
/// Our server HTTP handler to initiate HTTP upgrades.
fn server_upgrade(req: Request<Body>) -> Response<Body> {
let mut res = Response::new(Body::empty());
// Send a 400 to any request that doesn't have
// an `Upgrade` header.
if !req.headers().contains_key(UPGRADE) {
*res.status_mut() = StatusCode::BAD_REQUEST;
return res;
}
// Setup a future that will eventually receive the upgraded
// connection and talk a new protocol, and spawn the future
// into the runtime.
//
// Note: This can't possibly be fulfilled until the 101 response
// is returned below, so it's better to spawn this future instead
// waiting for it to complete to then return a response.
let on_upgrade = req
.into_body()
.on_upgrade()
.map_err(|err| eprintln!("upgrade error: {}", err))
.and_then(|upgraded| {
// We have an upgraded connection that we can read and
// write on directly.
//
// Since we completely control this example, we know exactly
// how many bytes the client will write, so just read exact...
tokio::io::read_exact(upgraded, vec![0; 7])
.and_then(|(upgraded, vec)| {
println!("server[foobar] recv: {:?}", str::from_utf8(&vec));
// And now write back the server 'foobar' protocol's
// response...
tokio::io::write_all(upgraded, b"bar=foo")
})
.map(|_| println!("server[foobar] sent"))
.map_err(|e| eprintln!("server foobar io error: {}", e))
});
rt::spawn(on_upgrade);
// Now return a 101 Response saying we agree to the upgrade to some
// made-up 'foobar' protocol.
*res.status_mut() = StatusCode::SWITCHING_PROTOCOLS;
res.headers_mut().insert(UPGRADE, HeaderValue::from_static("foobar"));
res
}
fn main() {
// For this example, we just make a server and our own client to talk to
// it, so the exact port isn't important. Instead, let the OS give us an
// unused port.
let addr = ([127, 0, 0, 1], 0).into();
let server = Server::bind(&addr)
.serve(|| service_fn_ok(server_upgrade));
// We need the assigned address for the client to send it messages.
let addr = server.local_addr();
// For this example, a oneshot is used to signal that after 1 request,
// the server should be shutdown.
let (tx, rx) = oneshot::channel();
let server = server
.map_err(|e| eprintln!("server error: {}", e))
.select2(rx)
.then(|_| Ok(()));
rt::run(rt::lazy(move || {
rt::spawn(server);
let req = Request::builder()
.uri(format!("http://{}/", addr))
.header(UPGRADE, "foobar")
.body(Body::empty())
.unwrap();
Client::new()
.request(req)
.and_then(|res| {
if res.status() != StatusCode::SWITCHING_PROTOCOLS {
panic!("Our server didn't upgrade: {}", res.status());
}
res
.into_body()
.on_upgrade()
})
.map_err(|e| eprintln!("client error: {}", e))
.and_then(|upgraded| {
// We've gotten an upgraded connection that we can read
// and write directly on. Let's start out 'foobar' protocol.
tokio::io::write_all(upgraded, b"foo=bar")
.and_then(|(upgraded, _)| {
println!("client[foobar] sent");
tokio::io::read_to_end(upgraded, Vec::new())
})
.map(|(_upgraded, vec)| {
println!("client[foobar] recv: {:?}", str::from_utf8(&vec));
// Complete the oneshot so that the server stops
// listening and the process can close down.
let _ = tx.send(());
})
.map_err(|e| eprintln!("client foobar io error: {}", e))
})
}));
}

View File

@@ -1,132 +0,0 @@
#![deny(warnings)]
extern crate futures;
extern crate hyper;
extern crate pretty_env_logger;
extern crate serde_json;
use futures::{future, Future, Stream};
use hyper::{Body, Chunk, Client, Method, Request, Response, Server, StatusCode, header};
use hyper::client::HttpConnector;
use hyper::service::service_fn;
static NOTFOUND: &[u8] = b"Not Found";
static URL: &str = "http://127.0.0.1:1337/json_api";
static INDEX: &[u8] = b"<a href=\"test.html\">test.html</a>";
static POST_DATA: &str = r#"{"original": "data"}"#;
type GenericError = Box<dyn std::error::Error + Send + Sync>;
type ResponseFuture = Box<dyn Future<Item=Response<Body>, Error=GenericError> + Send>;
fn client_request_response(client: &Client<HttpConnector>) -> ResponseFuture {
let req = Request::builder()
.method(Method::POST)
.uri(URL)
.header(header::CONTENT_TYPE, "application/json")
.body(POST_DATA.into())
.unwrap();
Box::new(client.request(req).from_err().map(|web_res| {
// Compare the JSON we sent (before) with what we received (after):
let body = Body::wrap_stream(web_res.into_body().map(|b| {
Chunk::from(format!("<b>POST request body</b>: {}<br><b>Response</b>: {}",
POST_DATA,
std::str::from_utf8(&b).unwrap()))
}));
Response::new(body)
}))
}
fn api_post_response(req: Request<Body>) -> ResponseFuture {
// A web api to run against
Box::new(req.into_body()
.concat2() // Concatenate all chunks in the body
.from_err()
.and_then(|entire_body| {
// TODO: Replace all unwraps with proper error handling
let str = String::from_utf8(entire_body.to_vec())?;
let mut data : serde_json::Value = serde_json::from_str(&str)?;
data["test"] = serde_json::Value::from("test_value");
let json = serde_json::to_string(&data)?;
let response = Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(json))?;
Ok(response)
})
)
}
fn api_get_response() -> ResponseFuture {
let data = vec!["foo", "bar"];
let res = match serde_json::to_string(&data) {
Ok(json) => {
Response::builder()
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(json))
.unwrap()
}
Err(_) => {
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Body::from("Internal Server Error"))
.unwrap()
}
};
Box::new(future::ok(res))
}
fn response_examples(req: Request<Body>, client: &Client<HttpConnector>) -> ResponseFuture {
match (req.method(), req.uri().path()) {
(&Method::GET, "/") | (&Method::GET, "/index.html") => {
let body = Body::from(INDEX);
Box::new(future::ok(Response::new(body)))
},
(&Method::GET, "/test.html") => {
client_request_response(client)
},
(&Method::POST, "/json_api") => {
api_post_response(req)
},
(&Method::GET, "/json_api") => {
api_get_response()
}
_ => {
// Return 404 not found response.
let body = Body::from(NOTFOUND);
Box::new(future::ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(body)
.unwrap()))
}
}
}
fn main() {
pretty_env_logger::init();
let addr = "127.0.0.1:1337".parse().unwrap();
hyper::rt::run(future::lazy(move || {
// Share a `Client` with all `Service`s
let client = Client::new();
let new_service = move || {
// Move a clone of `client` into the `service_fn`.
let client = client.clone();
service_fn(move |req| {
response_examples(req, &client)
})
};
let server = Server::bind(&addr)
.serve(new_service)
.map_err(|e| eprintln!("server error: {}", e));
println!("Listening on http://{}", addr);
server
}));
}