1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-27 17:52:56 +01:00

update actix api

This commit is contained in:
Nikolay Kim 2018-06-13 23:37:19 -07:00
parent c8528e8920
commit 8261cf437d
10 changed files with 100 additions and 95 deletions

View File

@ -311,9 +311,8 @@ pub struct ExtendedValue {
/// ; token except ( "*" / "'" / "%" )
/// ```
pub fn parse_extended_value(val: &str) -> Result<ExtendedValue, ::error::ParseError> {
// Break into three pieces separated by the single-quote character
let mut parts = val.splitn(3,'\'');
let mut parts = val.splitn(3, '\'');
// Interpret the first piece as a Charset
let charset: Charset = match parts.next() {
@ -322,13 +321,13 @@ pub fn parse_extended_value(val: &str) -> Result<ExtendedValue, ::error::ParseEr
};
// Interpret the second piece as a language tag
let lang: Option<LanguageTag> = match parts.next() {
let language_tag: Option<LanguageTag> = match parts.next() {
None => return Err(::error::ParseError::Header),
Some("") => None,
Some(s) => match s.parse() {
Ok(lt) => Some(lt),
Err(_) => return Err(::error::ParseError::Header),
}
},
};
// Interpret the third piece as a sequence of value characters
@ -338,17 +337,18 @@ pub fn parse_extended_value(val: &str) -> Result<ExtendedValue, ::error::ParseEr
};
Ok(ExtendedValue {
charset: charset,
language_tag: lang,
value: value,
value,
charset,
language_tag,
})
}
impl fmt::Display for ExtendedValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let encoded_value =
percent_encoding::percent_encode(&self.value[..], self::percent_encoding_http::HTTP_VALUE);
let encoded_value = percent_encoding::percent_encode(
&self.value[..],
self::percent_encoding_http::HTTP_VALUE,
);
if let Some(ref lang) = self.language_tag {
write!(f, "{}'{}'{}", self.charset, lang, encoded_value)
} else {
@ -362,7 +362,8 @@ impl fmt::Display for ExtendedValue {
///
/// [url]: https://tools.ietf.org/html/rfc5987#section-3.2
pub fn http_percent_encode(f: &mut fmt::Formatter, bytes: &[u8]) -> fmt::Result {
let encoded = percent_encoding::percent_encode(bytes, self::percent_encoding_http::HTTP_VALUE);
let encoded =
percent_encoding::percent_encode(bytes, self::percent_encoding_http::HTTP_VALUE);
fmt::Display::fmt(&encoded, f)
}
mod percent_encoding_http {
@ -382,8 +383,8 @@ mod percent_encoding_http {
#[cfg(test)]
mod tests {
use super::{parse_extended_value, ExtendedValue};
use header::shared::Charset;
use super::{ExtendedValue, parse_extended_value};
use language_tags::LanguageTag;
#[test]
@ -397,7 +398,10 @@ mod tests {
assert_eq!(Charset::Iso_8859_1, extended_value.charset);
assert!(extended_value.language_tag.is_some());
assert_eq!(expected_language_tag, extended_value.language_tag.unwrap());
assert_eq!(vec![163, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value);
assert_eq!(
vec![163, b' ', b'r', b'a', b't', b'e', b's'],
extended_value.value
);
}
#[test]
@ -410,7 +414,13 @@ mod tests {
let extended_value = result.unwrap();
assert_eq!(Charset::Ext("UTF-8".to_string()), extended_value.charset);
assert!(extended_value.language_tag.is_none());
assert_eq!(vec![194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value);
assert_eq!(
vec![
194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a',
b't', b'e', b's',
],
extended_value.value
);
}
#[test]
@ -447,10 +457,14 @@ mod tests {
let extended_value = ExtendedValue {
charset: Charset::Ext("UTF-8".to_string()),
language_tag: None,
value: vec![194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a',
b't', b'e', b's'],
value: vec![
194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a',
b't', b'e', b's',
],
};
assert_eq!("UTF-8''%C2%A3%20and%20%E2%82%AC%20rates",
format!("{}", extended_value));
assert_eq!(
"UTF-8''%C2%A3%20and%20%E2%82%AC%20rates",
format!("{}", extended_value)
);
}
}

View File

@ -147,16 +147,18 @@ impl HttpResponse {
#[inline]
pub fn cookies(&self) -> CookieIter {
CookieIter {
iter: self.get_ref().headers.get_all(header::SET_COOKIE).iter()
iter: self.get_ref().headers.get_all(header::SET_COOKIE).iter(),
}
}
/// Add a cookie to this response
#[inline]
pub fn add_cookie(&mut self, cookie: Cookie) -> Result<(), HttpError> {
pub fn add_cookie(&mut self, cookie: &Cookie) -> Result<(), HttpError> {
let h = &mut self.get_mut().headers;
HeaderValue::from_str(&cookie.to_string())
.map(|c| { h.append(header::SET_COOKIE, c); })
.map(|c| {
h.append(header::SET_COOKIE, c);
})
.map_err(|e| e.into())
}
@ -165,7 +167,8 @@ impl HttpResponse {
#[inline]
pub fn del_cookie(&mut self, name: &str) -> usize {
let h = &mut self.get_mut().headers;
let vals: Vec<HeaderValue> = h.get_all(header::SET_COOKIE)
let vals: Vec<HeaderValue> = h
.get_all(header::SET_COOKIE)
.iter()
.map(|v| v.to_owned())
.collect();
@ -183,7 +186,7 @@ impl HttpResponse {
}
h.append(header::SET_COOKIE, v);
}
return count;
count
}
/// Get the response status code
@ -333,7 +336,7 @@ impl<'a> Iterator for CookieIter<'a> {
#[inline]
fn next(&mut self) -> Option<Cookie<'a>> {
for v in self.iter.by_ref() {
if let Some(c) = (|| Cookie::parse(v.to_str().ok()?).ok())() {
if let Ok(c) = Cookie::parse(v.to_str().ok()?) {
return Some(c);
}
}
@ -1056,16 +1059,18 @@ mod tests {
);
}
#[test]
fn test_update_response_cookies() {
let mut r = HttpResponse::Ok()
.cookie(http::Cookie::new("original", "val100"))
.finish();
r.add_cookie(http::Cookie::new("cookie2", "val200")).unwrap();
r.add_cookie(http::Cookie::new("cookie2", "val250")).unwrap();
r.add_cookie(http::Cookie::new("cookie3", "val300")).unwrap();
r.add_cookie(&http::Cookie::new("cookie2", "val200"))
.unwrap();
r.add_cookie(&http::Cookie::new("cookie2", "val250"))
.unwrap();
r.add_cookie(&http::Cookie::new("cookie3", "val300"))
.unwrap();
assert_eq!(r.cookies().count(), 4);
r.del_cookie("cookie2");
@ -1287,7 +1292,8 @@ mod tests {
let mut resp: HttpResponse = "test".into();
assert_eq!(resp.status(), StatusCode::OK);
resp.add_cookie(http::Cookie::new("cookie1", "val100")).unwrap();
resp.add_cookie(&http::Cookie::new("cookie1", "val100"))
.unwrap();
let mut builder = resp.into_builder();
let resp = builder.status(StatusCode::BAD_REQUEST).finish();

View File

@ -58,7 +58,7 @@
//! )))
//! .bind("127.0.0.1:59880").unwrap()
//! .start();
//! # actix::Arbiter::system().do_send(actix::msgs::SystemExit(0));
//! # actix::System::current().stop();
//! });
//! }
//! ```

View File

@ -54,7 +54,7 @@ pub(crate) const MAX_WRITE_BUFFER_SIZE: usize = 65_536;
/// .bind("127.0.0.1:59090").unwrap()
/// .start();
///
/// # actix::Arbiter::system().do_send(actix::msgs::SystemExit(0));
/// # actix::System::current().stop();
/// });
/// }
/// ```

View File

@ -4,8 +4,8 @@ use std::time::Duration;
use std::{io, net, thread};
use actix::{
fut, msgs, signal, Actor, ActorContext, ActorFuture, Addr, Arbiter, AsyncContext,
Context, ContextFutureSpawner, Handler, Response, StreamHandler, System, WrapFuture,
fut, signal, Actor, ActorContext, ActorFuture, Addr, Arbiter, AsyncContext, Context,
ContextFutureSpawner, Handler, Response, StreamHandler, System, WrapFuture,
};
use futures::sync::mpsc;
@ -64,16 +64,8 @@ where
no_signals: bool,
}
unsafe impl<H> Sync for HttpServer<H>
where
H: IntoHttpHandler,
{
}
unsafe impl<H> Send for HttpServer<H>
where
H: IntoHttpHandler,
{
}
unsafe impl<H> Sync for HttpServer<H> where H: IntoHttpHandler {}
unsafe impl<H> Send for HttpServer<H> where H: IntoHttpHandler {}
enum ServerCommand {
WorkerDied(usize, Slab<SocketInfo>),
@ -170,10 +162,9 @@ where
self
}
/// Send `SystemExit` message to actix system
/// Stop actix system.
///
/// `SystemExit` message stops currently running system arbiter and all
/// nested arbiters.
/// `SystemExit` message stops currently running system.
pub fn system_exit(mut self) -> Self {
self.exit = true;
self
@ -388,7 +379,7 @@ where
if let Some(ref signals) = self.signals {
Some(signals.clone())
} else {
Some(Arbiter::registry().get::<signal::ProcessSignals>())
Some(System::current().registry().get::<signal::ProcessSignals>())
}
} else {
None
@ -418,7 +409,7 @@ impl<H: IntoHttpHandler> HttpServer<H> {
/// .bind("127.0.0.1:0")
/// .expect("Can not bind to 127.0.0.1:0")
/// .start();
/// # actix::Arbiter::system().do_send(actix::msgs::SystemExit(0));
/// # actix::System::current().stop();
/// });
/// }
/// ```
@ -597,7 +588,7 @@ impl<H: IntoHttpHandler> HttpServer<H> {
}
/// Signals support
/// Handle `SIGINT`, `SIGTERM`, `SIGQUIT` signals and send `SystemExit(0)`
/// Handle `SIGINT`, `SIGTERM`, `SIGQUIT` signals and stop actix system
/// message to `System` actor.
impl<H: IntoHttpHandler> Handler<signal::Signal> for HttpServer<H> {
type Result = ();
@ -753,7 +744,7 @@ impl<H: IntoHttpHandler> Handler<StopServer> for HttpServer<H> {
// we need to stop system if server was spawned
if slf.exit {
ctx.run_later(Duration::from_millis(300), |_, _| {
Arbiter::system().do_send(msgs::SystemExit(0))
System::current().stop();
});
}
}
@ -768,7 +759,7 @@ impl<H: IntoHttpHandler> Handler<StopServer> for HttpServer<H> {
// we need to stop system if server was spawned
if self.exit {
ctx.run_later(Duration::from_millis(300), |_, _| {
Arbiter::system().do_send(msgs::SystemExit(0))
System::current().stop();
});
}
Response::reply(Ok(()))

View File

@ -95,14 +95,14 @@ impl<H: HttpHandler + 'static> Worker<H> {
let num = slf.settings.num_channels();
if num == 0 {
let _ = tx.send(true);
Arbiter::arbiter().do_send(StopArbiter(0));
Arbiter::current().do_send(StopArbiter(0));
} else if let Some(d) = dur.checked_sub(time::Duration::new(1, 0)) {
slf.shutdown_timeout(ctx, tx, d);
} else {
info!("Force shutdown http worker, {} connections", num);
slf.settings.head().traverse::<TcpStream, H>();
let _ = tx.send(false);
Arbiter::arbiter().do_send(StopArbiter(0));
Arbiter::current().do_send(StopArbiter(0));
}
});
}

View File

@ -4,7 +4,7 @@ use std::str::FromStr;
use std::sync::mpsc;
use std::{net, thread};
use actix_inner::{msgs, Actor, Addr, Arbiter, System};
use actix_inner::{Actor, Addr, System};
use cookie::Cookie;
use futures::Future;
@ -59,7 +59,6 @@ use ws;
/// ```
pub struct TestServer {
addr: net::SocketAddr,
server_sys: Addr<System>,
ssl: bool,
conn: Addr<ClientConnector>,
rt: Runtime,
@ -116,20 +115,15 @@ impl TestServer {
.listen(tcp)
.start();
tx.send((
Arbiter::system(),
local_addr,
TestServer::get_conn(),
Arbiter::registry().clone(),
)).unwrap();
tx.send((System::current(), local_addr, TestServer::get_conn()))
.unwrap();
}).run();
});
let (server_sys, addr, conn, reg) = rx.recv().unwrap();
Arbiter::set_system_reg(reg);
let (system, addr, conn) = rx.recv().unwrap();
System::set_current(system);
TestServer {
addr,
server_sys,
conn,
ssl: false,
rt: Runtime::new().unwrap(),
@ -187,7 +181,7 @@ impl TestServer {
/// Stop http server
fn stop(&mut self) {
self.server_sys.do_send(msgs::SystemExit(0));
System::current().stop();
}
/// Execute future on current core
@ -296,12 +290,8 @@ impl<S: 'static> TestServerBuilder<S> {
}).workers(1)
.disable_signals();
tx.send((
Arbiter::system(),
local_addr,
TestServer::get_conn(),
Arbiter::registry().clone(),
)).unwrap();
tx.send((System::current(), local_addr, TestServer::get_conn()))
.unwrap();
#[cfg(feature = "alpn")]
{
@ -320,13 +310,12 @@ impl<S: 'static> TestServerBuilder<S> {
.run();
});
let (server_sys, addr, conn, reg) = rx.recv().unwrap();
Arbiter::set_system_reg(reg);
let (system, addr, conn) = rx.recv().unwrap();
System::set_current(system);
TestServer {
addr,
ssl,
conn,
server_sys,
rt: Runtime::new().unwrap(),
}
}

View File

@ -105,9 +105,8 @@ struct FormData {
fn test_form_extractor() {
let mut srv = test::TestServer::new(|app| {
app.resource("/{username}/index.html", |r| {
r.route().with(|form: Form<FormData>| {
format!("{}", form.username)
})
r.route()
.with(|form: Form<FormData>| format!("{}", form.username))
});
});
@ -115,7 +114,9 @@ fn test_form_extractor() {
let request = srv
.post()
.uri(srv.url("/test1/index.html"))
.form(FormData{username: "test".to_string()})
.form(FormData {
username: "test".to_string(),
})
.unwrap();
let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success());
@ -129,12 +130,14 @@ fn test_form_extractor() {
fn test_form_extractor2() {
let mut srv = test::TestServer::new(|app| {
app.resource("/{username}/index.html", |r| {
r.route().with(|form: Form<FormData>| {
format!("{}", form.username)
}).error_handler(|err, res| {
error::InternalError::from_response(
err, HttpResponse::Conflict().finish()).into()
});
r.route()
.with(|form: Form<FormData>| format!("{}", form.username))
.error_handler(|err, _| {
error::InternalError::from_response(
err,
HttpResponse::Conflict().finish(),
).into()
});
});
});

View File

@ -839,7 +839,7 @@ fn test_middleware_chain_with_error() {
});
let request = srv.get().uri(srv.url("/test")).finish().unwrap();
let response = srv.execute(request.send()).unwrap();
srv.execute(request.send()).unwrap();
assert_eq!(num1.load(Ordering::Relaxed), 1);
assert_eq!(num2.load(Ordering::Relaxed), 1);
@ -869,7 +869,7 @@ fn test_middleware_async_chain_with_error() {
});
let request = srv.get().uri(srv.url("/test")).finish().unwrap();
let response = srv.execute(request.send()).unwrap();
srv.execute(request.send()).unwrap();
assert_eq!(num1.load(Ordering::Relaxed), 1);
assert_eq!(num2.load(Ordering::Relaxed), 1);
@ -901,7 +901,7 @@ fn test_scope_middleware_chain_with_error() {
});
let request = srv.get().uri(srv.url("/scope/test")).finish().unwrap();
let response = srv.execute(request.send()).unwrap();
srv.execute(request.send()).unwrap();
assert_eq!(num1.load(Ordering::Relaxed), 1);
assert_eq!(num2.load(Ordering::Relaxed), 1);
@ -933,7 +933,7 @@ fn test_scope_middleware_async_chain_with_error() {
});
let request = srv.get().uri(srv.url("/scope/test")).finish().unwrap();
let response = srv.execute(request.send()).unwrap();
srv.execute(request.send()).unwrap();
assert_eq!(num1.load(Ordering::Relaxed), 1);
assert_eq!(num2.load(Ordering::Relaxed), 1);
@ -964,7 +964,7 @@ fn test_resource_middleware_chain_with_error() {
});
let request = srv.get().uri(srv.url("/test")).finish().unwrap();
let response = srv.execute(request.send()).unwrap();
srv.execute(request.send()).unwrap();
assert_eq!(num1.load(Ordering::Relaxed), 1);
assert_eq!(num2.load(Ordering::Relaxed), 1);
@ -995,7 +995,7 @@ fn test_resource_middleware_async_chain_with_error() {
});
let request = srv.get().uri(srv.url("/test")).finish().unwrap();
let response = srv.execute(request.send()).unwrap();
srv.execute(request.send()).unwrap();
assert_eq!(num1.load(Ordering::Relaxed), 1);
assert_eq!(num2.load(Ordering::Relaxed), 1);

View File

@ -32,7 +32,7 @@ use tokio::executor::current_thread;
use tokio::runtime::current_thread::Runtime;
use tokio_tcp::TcpStream;
use actix::{msgs, Arbiter, System};
use actix::System;
use actix_web::*;
const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
@ -74,10 +74,11 @@ fn test_start() {
let srv = srv.bind("127.0.0.1:0").unwrap();
let addr = srv.addrs()[0];
let srv_addr = srv.start();
let _ = tx.send((addr, srv_addr, Arbiter::system()));
let _ = tx.send((addr, srv_addr, System::current()));
});
});
let (addr, srv_addr, sys) = rx.recv().unwrap();
System::set_current(sys.clone());
let mut rt = Runtime::new().unwrap();
{
@ -110,7 +111,7 @@ fn test_start() {
assert!(response.status().is_success());
}
let _ = sys.send(msgs::SystemExit(0)).wait();
let _ = sys.stop();
}
#[test]
@ -130,10 +131,11 @@ fn test_shutdown() {
let srv = srv.bind("127.0.0.1:0").unwrap();
let addr = srv.addrs()[0];
let srv_addr = srv.shutdown_timeout(1).start();
let _ = tx.send((addr, srv_addr, Arbiter::system()));
let _ = tx.send((addr, srv_addr, System::current()));
});
});
let (addr, srv_addr, sys) = rx.recv().unwrap();
System::set_current(sys.clone());
let mut rt = Runtime::new().unwrap();
{
@ -148,7 +150,7 @@ fn test_shutdown() {
thread::sleep(time::Duration::from_millis(1000));
assert!(net::TcpStream::connect(addr).is_err());
let _ = sys.send(msgs::SystemExit(0)).wait();
let _ = sys.stop();
}
#[test]