style(lib): run rustfmt and enforce in CI
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
#![warn(rust_2018_idioms)]
|
||||
use std::env;
|
||||
|
||||
use hyper::{Client, body::HttpBody as _};
|
||||
use hyper::{body::HttpBody as _, Client};
|
||||
use tokio::io::{self, AsyncWriteExt as _};
|
||||
|
||||
// A simple type alias so as to DRY.
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
#[macro_use]
|
||||
extern crate serde_derive;
|
||||
|
||||
use hyper::Client;
|
||||
use futures_util::StreamExt;
|
||||
use hyper::Client;
|
||||
|
||||
// A simple type alias so as to DRY.
|
||||
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
|
||||
|
||||
@@ -1,22 +1,20 @@
|
||||
//#![deny(warnings)]
|
||||
|
||||
use hyper::{Body, Method, Request, Response, Server, StatusCode};
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use futures_util::{StreamExt, TryStreamExt};
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use hyper::{Body, Method, Request, Response, Server, StatusCode};
|
||||
|
||||
/// This is our service handler. It receives a Request, routes on its
|
||||
/// path, and returns a Future of a Response.
|
||||
async fn echo(mut req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
|
||||
match (req.method(), req.uri().path()) {
|
||||
// Serve some instructions at /
|
||||
(&Method::GET, "/") => {
|
||||
Ok(Response::new(Body::from("Try POSTing data to /echo such as: `curl localhost:3000/echo -XPOST -d 'hello world'`")))
|
||||
}
|
||||
(&Method::GET, "/") => Ok(Response::new(Body::from(
|
||||
"Try POSTing data to /echo such as: `curl localhost:3000/echo -XPOST -d 'hello world'`",
|
||||
))),
|
||||
|
||||
// Simply echo the body back to the client.
|
||||
(&Method::POST, "/echo") => {
|
||||
Ok(Response::new(req.into_body()))
|
||||
}
|
||||
(&Method::POST, "/echo") => Ok(Response::new(req.into_body())),
|
||||
|
||||
// Convert to uppercase before sending back to client using a stream.
|
||||
(&Method::POST, "/echo/uppercase") => {
|
||||
@@ -41,11 +39,7 @@ async fn echo(mut req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
|
||||
whole_body.extend_from_slice(&chunk?);
|
||||
}
|
||||
|
||||
let reversed_body = whole_body
|
||||
.iter()
|
||||
.rev()
|
||||
.cloned()
|
||||
.collect::<Vec<u8>>();
|
||||
let reversed_body = whole_body.iter().rev().cloned().collect::<Vec<u8>>();
|
||||
Ok(Response::new(Body::from(reversed_body)))
|
||||
}
|
||||
|
||||
@@ -58,19 +52,13 @@ async fn echo(mut req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let addr = ([127, 0, 0, 1], 3000).into();
|
||||
|
||||
let service = make_service_fn(|_| {
|
||||
async {
|
||||
Ok::<_, hyper::Error>(service_fn(echo))
|
||||
}
|
||||
});
|
||||
let service = make_service_fn(|_| async { Ok::<_, hyper::Error>(service_fn(echo)) });
|
||||
|
||||
let server = Server::bind(&addr)
|
||||
.serve(service);
|
||||
let server = Server::bind(&addr).serve(service);
|
||||
|
||||
println!("Listening on http://{}", addr);
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
use std::convert::Infallible;
|
||||
|
||||
use hyper::{Body, Request, Response, Server};
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use hyper::{Body, Request, Response, Server};
|
||||
|
||||
async fn hello(_: Request<Body>) -> Result<Response<Body>, Infallible> {
|
||||
Ok(Response::new(Body::from("Hello World!")))
|
||||
@@ -19,9 +19,7 @@ pub async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
// This is the `Service` that will handle the connection.
|
||||
// `service_fn` is a helper to convert a function that
|
||||
// returns a Response into a `Service`.
|
||||
async {
|
||||
Ok::<_, Infallible>(service_fn(hello))
|
||||
}
|
||||
async { Ok::<_, Infallible>(service_fn(hello)) }
|
||||
});
|
||||
|
||||
let addr = ([127, 0, 0, 1], 3000).into();
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#![deny(warnings)]
|
||||
#![warn(rust_2018_idioms)]
|
||||
|
||||
use hyper::{Body, Request, Response, Server};
|
||||
use hyper::service::{service_fn, make_service_fn};
|
||||
use futures_util::future::join;
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use hyper::{Body, Request, Response, Server};
|
||||
|
||||
static INDEX1: &'static [u8] = b"The 1st service!";
|
||||
static INDEX2: &'static [u8] = b"The 2nd service!";
|
||||
@@ -23,19 +23,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let addr1 = ([127, 0, 0, 1], 1337).into();
|
||||
let addr2 = ([127, 0, 0, 1], 1338).into();
|
||||
|
||||
let srv1 = Server::bind(&addr1)
|
||||
.serve(make_service_fn(|_| {
|
||||
async {
|
||||
Ok::<_, hyper::Error>(service_fn(index1))
|
||||
}
|
||||
}));
|
||||
let srv1 = Server::bind(&addr1).serve(make_service_fn(|_| {
|
||||
async { Ok::<_, hyper::Error>(service_fn(index1)) }
|
||||
}));
|
||||
|
||||
let srv2 = Server::bind(&addr2)
|
||||
.serve(make_service_fn(|_| {
|
||||
async {
|
||||
Ok::<_, hyper::Error>(service_fn(index2))
|
||||
}
|
||||
}));
|
||||
let srv2 = Server::bind(&addr2).serve(make_service_fn(|_| {
|
||||
async { Ok::<_, hyper::Error>(service_fn(index2)) }
|
||||
}));
|
||||
|
||||
println!("Listening on http://{} and http://{}", addr1, addr2);
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
// #![deny(warnings)] // FIXME: https://github.com/rust-lang/rust/issues/62411
|
||||
#![warn(rust_2018_idioms)]
|
||||
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use hyper::{Body, Method, Request, Response, Server, StatusCode};
|
||||
use hyper::service::{service_fn, make_service_fn};
|
||||
|
||||
use futures_util::StreamExt;
|
||||
use std::collections::HashMap;
|
||||
use url::form_urlencoded;
|
||||
use futures_util::StreamExt;
|
||||
|
||||
static INDEX: &[u8] = b"<html><body><form action=\"post\" method=\"post\">Name: <input type=\"text\" name=\"name\"><br>Number: <input type=\"text\" name=\"number\"><br><input type=\"submit\"></body></html>";
|
||||
static MISSING: &[u8] = b"Missing field";
|
||||
@@ -15,9 +15,7 @@ static NOTNUMERIC: &[u8] = b"Number field is not numeric";
|
||||
// Using service_fn, we can turn this function into a `Service`.
|
||||
async fn param_example(mut req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
|
||||
match (req.method(), req.uri().path()) {
|
||||
(&Method::GET, "/") | (&Method::GET, "/post") => {
|
||||
Ok(Response::new(INDEX.into()))
|
||||
},
|
||||
(&Method::GET, "/") | (&Method::GET, "/post") => Ok(Response::new(INDEX.into())),
|
||||
(&Method::POST, "/post") => {
|
||||
// Concatenate the body...
|
||||
let mut b = Vec::new();
|
||||
@@ -35,7 +33,9 @@ async fn param_example(mut req: Request<Body>) -> Result<Response<Body>, hyper::
|
||||
// form, and the values should be rolled up into a
|
||||
// HashMap<String, Vec<String>>. However in this
|
||||
// example the simpler approach is sufficient.
|
||||
let params = form_urlencoded::parse(b.as_ref()).into_owned().collect::<HashMap<String, String>>();
|
||||
let params = form_urlencoded::parse(b.as_ref())
|
||||
.into_owned()
|
||||
.collect::<HashMap<String, String>>();
|
||||
|
||||
// Validate the request parameters, returning
|
||||
// early if an invalid input is detected.
|
||||
@@ -71,13 +71,11 @@ async fn param_example(mut req: Request<Body>) -> Result<Response<Body>, hyper::
|
||||
// needed here, too.
|
||||
let body = format!("Hello {}, your number is {}", name, number);
|
||||
Ok(Response::new(body.into()))
|
||||
},
|
||||
_ => {
|
||||
Ok(Response::builder()
|
||||
.status(StatusCode::NOT_FOUND)
|
||||
.body(Body::empty())
|
||||
.unwrap())
|
||||
}
|
||||
_ => Ok(Response::builder()
|
||||
.status(StatusCode::NOT_FOUND)
|
||||
.body(Body::empty())
|
||||
.unwrap()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,12 +85,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
|
||||
let addr = ([127, 0, 0, 1], 1337).into();
|
||||
|
||||
let server = Server::bind(&addr)
|
||||
.serve(make_service_fn(|_| {
|
||||
async {
|
||||
Ok::<_, hyper::Error>(service_fn(param_example))
|
||||
}
|
||||
}));
|
||||
let server = Server::bind(&addr).serve(make_service_fn(|_| {
|
||||
async { Ok::<_, hyper::Error>(service_fn(param_example)) }
|
||||
}));
|
||||
|
||||
println!("Listening on http://{}", addr);
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#![deny(warnings)]
|
||||
|
||||
use hyper::{Client, Error, Server};
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use hyper::{Client, Error, Server};
|
||||
use std::net::SocketAddr;
|
||||
|
||||
#[tokio::main]
|
||||
@@ -19,15 +19,17 @@ async fn main() {
|
||||
// creating a 'service' to handle requests for that specific connection.
|
||||
let make_service = make_service_fn(move |_| {
|
||||
let client = client_main.clone();
|
||||
|
||||
|
||||
async move {
|
||||
// This is the `Service` that will handle the connection.
|
||||
// `service_fn` is a helper to convert a function that
|
||||
// returns a Response into a `Service`.
|
||||
Ok::<_, Error>(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_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)
|
||||
@@ -35,8 +37,7 @@ async fn main() {
|
||||
}
|
||||
});
|
||||
|
||||
let server = Server::bind(&in_addr)
|
||||
.serve(make_service);
|
||||
let server = Server::bind(&in_addr).serve(make_service);
|
||||
|
||||
println!("Listening on http://{}", in_addr);
|
||||
println!("Proxying on http://{}", out_addr);
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
#![deny(warnings)]
|
||||
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::fs::File;
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
use hyper::{Body, Method, Result, Request, Response, Server, StatusCode};
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use hyper::{Body, Method, Request, Response, Result, Server, StatusCode};
|
||||
|
||||
static INDEX: &str = "examples/send_file_index.html";
|
||||
static INTERNAL_SERVER_ERROR: &[u8] = b"Internal Server Error";
|
||||
@@ -16,12 +16,10 @@ async fn main() {
|
||||
|
||||
let addr = "127.0.0.1:1337".parse().unwrap();
|
||||
|
||||
let make_service = make_service_fn(|_| async {
|
||||
Ok::<_, hyper::Error>(service_fn(response_examples))
|
||||
});
|
||||
let make_service =
|
||||
make_service_fn(|_| async { Ok::<_, hyper::Error>(service_fn(response_examples)) });
|
||||
|
||||
let server = Server::bind(&addr)
|
||||
.serve(make_service);
|
||||
let server = Server::bind(&addr).serve(make_service);
|
||||
|
||||
println!("Listening on http://{}", addr);
|
||||
|
||||
@@ -32,16 +30,14 @@ async fn main() {
|
||||
|
||||
async fn response_examples(req: Request<Body>) -> Result<Response<Body>> {
|
||||
match (req.method(), req.uri().path()) {
|
||||
(&Method::GET, "/") |
|
||||
(&Method::GET, "/index.html") |
|
||||
(&Method::GET, "/big_file.html") => {
|
||||
(&Method::GET, "/") | (&Method::GET, "/index.html") | (&Method::GET, "/big_file.html") => {
|
||||
simple_file_send(INDEX).await
|
||||
}
|
||||
(&Method::GET, "/no_file.html") => {
|
||||
// Test what happens when file cannot be be found
|
||||
simple_file_send("this_file_should_not_exist.html").await
|
||||
}
|
||||
_ => Ok(not_found())
|
||||
_ => Ok(not_found()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use hyper::{Body, Error, Response, Server};
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use hyper::{Body, Error, Response, Server};
|
||||
|
||||
fn main() {
|
||||
pretty_env_logger::init();
|
||||
@@ -22,7 +22,6 @@ fn main() {
|
||||
}
|
||||
|
||||
async fn run() {
|
||||
|
||||
let addr = ([127, 0, 0, 1], 3000).into();
|
||||
|
||||
// Using a !Send request counter is fine on 1 thread...
|
||||
@@ -37,18 +36,12 @@ async fn run() {
|
||||
let prev = cnt.get();
|
||||
cnt.set(prev + 1);
|
||||
let value = cnt.get();
|
||||
async move {
|
||||
Ok::<_, Error>(Response::new(Body::from(
|
||||
format!("Request #{}", value)
|
||||
)))
|
||||
}
|
||||
async move { Ok::<_, Error>(Response::new(Body::from(format!("Request #{}", value)))) }
|
||||
}))
|
||||
}
|
||||
});
|
||||
|
||||
let server = Server::bind(&addr)
|
||||
.executor(LocalExec)
|
||||
.serve(make_service);
|
||||
let server = Server::bind(&addr).executor(LocalExec).serve(make_service);
|
||||
|
||||
println!("Listening on http://{}", addr);
|
||||
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
#![deny(warnings)]
|
||||
|
||||
use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
|
||||
use std::sync::{
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
use hyper::{Body, Error, Response, Server};
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use hyper::{Body, Error, Response, Server};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
@@ -34,17 +37,12 @@ async fn main() {
|
||||
// Get the current count, and also increment by 1, in a single
|
||||
// atomic operation.
|
||||
let count = counter.fetch_add(1, Ordering::AcqRel);
|
||||
async move {
|
||||
Ok::<_, Error>(
|
||||
Response::new(Body::from(format!("Request #{}", count)))
|
||||
)
|
||||
}
|
||||
async move { Ok::<_, Error>(Response::new(Body::from(format!("Request #{}", count)))) }
|
||||
}))
|
||||
}
|
||||
});
|
||||
|
||||
let server = Server::bind(&addr)
|
||||
.serve(make_service);
|
||||
let server = Server::bind(&addr).serve(make_service);
|
||||
|
||||
println!("Listening on http://{}", addr);
|
||||
|
||||
@@ -52,4 +50,3 @@ async fn main() {
|
||||
eprintln!("server error: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#![deny(warnings)]
|
||||
|
||||
use hyper::client::service::Connect;
|
||||
use hyper::client::conn::Builder;
|
||||
use hyper::client::connect::HttpConnector;
|
||||
use hyper::client::service::Connect;
|
||||
use hyper::service::Service;
|
||||
use hyper::{Body, Request};
|
||||
|
||||
@@ -14,7 +14,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
let uri = "http://127.0.0.1:8080".parse::<http::Uri>()?;
|
||||
|
||||
|
||||
let mut svc = mk_svc.call(uri.clone()).await?;
|
||||
|
||||
let body = Body::empty();
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use futures_util::future;
|
||||
use hyper::{Body, Request, Response, Server};
|
||||
use hyper::service::Service;
|
||||
use hyper::{Body, Request, Response, Server};
|
||||
|
||||
const ROOT: &'static str = "/";
|
||||
|
||||
@@ -58,9 +58,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
let addr = "127.0.0.1:1337".parse().unwrap();
|
||||
|
||||
|
||||
let server = Server::bind(&addr)
|
||||
.serve(MakeSvc);
|
||||
let server = Server::bind(&addr).serve(MakeSvc);
|
||||
|
||||
println!("Listening on http://{}", addr);
|
||||
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
// Note: `hyper::upgrade` docs link to this upgrade.
|
||||
use std::str;
|
||||
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use hyper::{Body, Client, Request, Response, Server, StatusCode};
|
||||
use hyper::header::{UPGRADE, HeaderValue};
|
||||
use hyper::header::{HeaderValue, UPGRADE};
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use hyper::upgrade::Upgraded;
|
||||
use hyper::{Body, Client, Request, Response, Server, StatusCode};
|
||||
use std::net::SocketAddr;
|
||||
|
||||
// A simple type alias so as to DRY.
|
||||
@@ -58,14 +58,15 @@ async fn server_upgrade(req: Request<Body>) -> Result<Response<Body>> {
|
||||
eprintln!("server foobar io error: {}", e)
|
||||
};
|
||||
}
|
||||
Err(e) => eprintln!("upgrade error: {}", e)
|
||||
Err(e) => eprintln!("upgrade error: {}", e),
|
||||
}
|
||||
});
|
||||
|
||||
// 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.headers_mut()
|
||||
.insert(UPGRADE, HeaderValue::from_static("foobar"));
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
@@ -102,7 +103,7 @@ async fn client_upgrade_request(addr: SocketAddr) -> Result<()> {
|
||||
eprintln!("client foobar io error: {}", e)
|
||||
};
|
||||
}
|
||||
Err(e) => eprintln!("upgrade error: {}", e)
|
||||
Err(e) => eprintln!("upgrade error: {}", e),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -115,12 +116,10 @@ async fn main() {
|
||||
// unused port.
|
||||
let addr = ([127, 0, 0, 1], 0).into();
|
||||
|
||||
let make_service = make_service_fn(|_| async {
|
||||
Ok::<_, hyper::Error>(service_fn(server_upgrade))
|
||||
});
|
||||
let make_service =
|
||||
make_service_fn(|_| async { Ok::<_, hyper::Error>(service_fn(server_upgrade)) });
|
||||
|
||||
let server = Server::bind(&addr)
|
||||
.serve(make_service);
|
||||
let server = Server::bind(&addr).serve(make_service);
|
||||
|
||||
// We need the assigned address for the client to send it messages.
|
||||
let addr = server.local_addr();
|
||||
@@ -128,10 +127,9 @@ async fn main() {
|
||||
// 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
|
||||
.with_graceful_shutdown(async move {
|
||||
rx.await.ok();
|
||||
});
|
||||
let server = server.with_graceful_shutdown(async move {
|
||||
rx.await.ok();
|
||||
});
|
||||
|
||||
// Spawn server on the default executor,
|
||||
// which is usually a thread-pool from tokio default runtime.
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#![deny(warnings)]
|
||||
|
||||
use hyper::{Body, Chunk, Client, Method, Request, Response, Server, StatusCode, header};
|
||||
use futures_util::{StreamExt, TryStreamExt};
|
||||
use hyper::client::HttpConnector;
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use futures_util::{StreamExt, TryStreamExt};
|
||||
use hyper::{header, Body, Chunk, Client, Method, Request, Response, Server, StatusCode};
|
||||
|
||||
type GenericError = Box<dyn std::error::Error + Send + Sync>;
|
||||
type Result<T> = std::result::Result<T, GenericError>;
|
||||
@@ -14,9 +14,7 @@ static NOTFOUND: &[u8] = b"Not Found";
|
||||
static POST_DATA: &str = r#"{"original": "data"}"#;
|
||||
static URL: &str = "http://127.0.0.1:1337/json_api";
|
||||
|
||||
async fn client_request_response(
|
||||
client: &Client<HttpConnector>
|
||||
) -> Result<Response<Body>> {
|
||||
async fn client_request_response(client: &Client<HttpConnector>) -> Result<Response<Body>> {
|
||||
let req = Request::builder()
|
||||
.method(Method::POST)
|
||||
.uri(URL)
|
||||
@@ -27,9 +25,11 @@ async fn client_request_response(
|
||||
let web_res = client.request(req).await?;
|
||||
// Compare the JSON we sent (before) with what we received (after):
|
||||
let body = Body::wrap_stream(web_res.into_body().map_ok(|b| {
|
||||
Chunk::from(format!("<b>POST request body</b>: {}<br><b>Response</b>: {}",
|
||||
POST_DATA,
|
||||
std::str::from_utf8(&b).unwrap()))
|
||||
Chunk::from(format!(
|
||||
"<b>POST request body</b>: {}<br><b>Response</b>: {}",
|
||||
POST_DATA,
|
||||
std::str::from_utf8(&b).unwrap()
|
||||
))
|
||||
}));
|
||||
|
||||
Ok(Response::new(body))
|
||||
@@ -57,40 +57,27 @@ async fn api_post_response(mut req: Request<Body>) -> Result<Response<Body>> {
|
||||
async fn api_get_response() -> Result<Response<Body>> {
|
||||
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(INTERNAL_SERVER_ERROR.into())
|
||||
.unwrap()
|
||||
}
|
||||
Ok(json) => Response::builder()
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(json))
|
||||
.unwrap(),
|
||||
Err(_) => Response::builder()
|
||||
.status(StatusCode::INTERNAL_SERVER_ERROR)
|
||||
.body(INTERNAL_SERVER_ERROR.into())
|
||||
.unwrap(),
|
||||
};
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
async fn response_examples(
|
||||
req: Request<Body>,
|
||||
client: Client<HttpConnector>
|
||||
client: Client<HttpConnector>,
|
||||
) -> Result<Response<Body>> {
|
||||
match (req.method(), req.uri().path()) {
|
||||
(&Method::GET, "/") |
|
||||
(&Method::GET, "/index.html") => {
|
||||
Ok(Response::new(INDEX.into()))
|
||||
},
|
||||
(&Method::GET, "/test.html") => {
|
||||
client_request_response(&client).await
|
||||
},
|
||||
(&Method::POST, "/json_api") => {
|
||||
api_post_response(req).await
|
||||
},
|
||||
(&Method::GET, "/json_api") => {
|
||||
api_get_response().await
|
||||
}
|
||||
(&Method::GET, "/") | (&Method::GET, "/index.html") => Ok(Response::new(INDEX.into())),
|
||||
(&Method::GET, "/test.html") => client_request_response(&client).await,
|
||||
(&Method::POST, "/json_api") => api_post_response(req).await,
|
||||
(&Method::GET, "/json_api") => api_get_response().await,
|
||||
_ => {
|
||||
// Return 404 not found response.
|
||||
Ok(Response::builder()
|
||||
@@ -121,8 +108,7 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
});
|
||||
|
||||
let server = Server::bind(&addr)
|
||||
.serve(new_service);
|
||||
let server = Server::bind(&addr).serve(new_service);
|
||||
|
||||
println!("Listening on http://{}", addr);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user