1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-24 00:21:08 +01:00

better naming

This commit is contained in:
Nikolay Kim 2017-10-08 14:56:51 -07:00
parent 3036152581
commit 63b78b6461
11 changed files with 100 additions and 81 deletions

View File

@ -25,13 +25,15 @@ path = "src/main.rs"
time = "0.1"
http = "0.1"
httparse = "0.1"
hyper = "0.11"
unicase = "2.0"
slab = "0.4"
sha1 = "0.2"
rand = "0.3"
url = "1.5"
route-recognizer = "0.1"
hyper = "0.11"
unicase = "2.0"
# tokio
bytes = "0.4"
futures = "0.1"

View File

@ -1,4 +1,4 @@
# Actix Http [![Build Status](https://travis-ci.org/fafhrd91/actix-http.svg?branch=master)](https://travis-ci.org/fafhrd91/actix-http)
# Actix http [![Build Status](https://travis-ci.org/fafhrd91/actix-http.svg?branch=master)](https://travis-ci.org/fafhrd91/actix-http)
Actix http is a server http framework for Actix framework.
@ -8,7 +8,7 @@ Actix http is a server http framework for Actix framework.
---
Actix Http is licensed under the [Apache-2.0 license](http://opensource.org/licenses/APACHE-2.0).
Actix http is licensed under the [Apache-2.0 license](http://opensource.org/licenses/APACHE-2.0).
## Features
@ -49,9 +49,9 @@ impl Route for MyRoute {
type State = ();
fn request(req: HttpRequest, payload: Option<Payload>,
ctx: &mut HttpContext<Self>) -> HttpMessage<Self>
ctx: &mut HttpContext<Self>) -> Reply<Self>
{
HttpMessage::reply_with(req, httpcodes::HTTPOk)
Reply::with(req, httpcodes::HTTPOk)
}
}

View File

@ -6,21 +6,21 @@ use route_recognizer::Router;
use task::Task;
use route::{Payload, RouteHandler};
use router::HttpHandler;
use resource::HttpResource;
use router::Handler;
use resource::Resource;
use httpmessage::HttpRequest;
/// Application
pub struct HttpApplication<S=()> {
pub struct Application<S=()> {
state: S,
default: HttpResource<S>,
resources: HashMap<String, HttpResource<S>>,
default: Resource<S>,
resources: HashMap<String, Resource<S>>,
}
impl<S> HttpApplication<S> where S: 'static
impl<S> Application<S> where S: 'static
{
pub(crate) fn prepare(self, prefix: String) -> Box<HttpHandler> {
pub(crate) fn prepare(self, prefix: String) -> Box<Handler> {
let mut router = Router::new();
let prefix = if prefix.ends_with('/') {prefix } else { prefix + "/" };
@ -38,46 +38,46 @@ impl<S> HttpApplication<S> where S: 'static
}
}
impl HttpApplication<()> {
impl Default for Application<()> {
/// Create `HttpApplication` with no state
pub fn no_state() -> Self {
HttpApplication {
/// Create default `Application` with no state
fn default() -> Self {
Application {
state: (),
default: HttpResource::default(),
default: Resource::default(),
resources: HashMap::new(),
}
}
}
impl<S> HttpApplication<S> where S: 'static {
impl<S> Application<S> where S: 'static {
/// Create http application with specific state. State is shared with all
/// routes within same application and could be
/// accessed with `HttpContext::state()` method.
pub fn new(state: S) -> HttpApplication<S> {
HttpApplication {
pub fn new(state: S) -> Application<S> {
Application {
state: state,
default: HttpResource::default(),
default: Resource::default(),
resources: HashMap::new(),
}
}
/// Add resource by path.
pub fn add<P: ToString>(&mut self, path: P) -> &mut HttpResource<S>
pub fn add<P: ToString>(&mut self, path: P) -> &mut Resource<S>
{
let path = path.to_string();
// add resource
if !self.resources.contains_key(&path) {
self.resources.insert(path.clone(), HttpResource::default());
self.resources.insert(path.clone(), Resource::default());
}
self.resources.get_mut(&path).unwrap()
}
/// Default resource is used if no matched route could be found.
pub fn default(&mut self) -> &mut HttpResource<S> {
/// Default resource is used if no matches route could be found.
pub fn default_resource(&mut self) -> &mut Resource<S> {
&mut self.default
}
}
@ -86,12 +86,12 @@ impl<S> HttpApplication<S> where S: 'static {
pub(crate)
struct InnerApplication<S> {
state: Rc<S>,
default: HttpResource<S>,
router: Router<HttpResource<S>>,
default: Resource<S>,
router: Router<Resource<S>>,
}
impl<S: 'static> HttpHandler for InnerApplication<S> {
impl<S: 'static> Handler for InnerApplication<S> {
fn handle(&self, req: HttpRequest, payload: Option<Payload>) -> Task {
if let Ok(h) = self.router.recognize(req.path()) {

View File

@ -164,6 +164,21 @@ impl HttpRequest {
}
}
/// Is keepalive enabled by client?
pub fn keep_alive(&self) -> bool {
let ret = match (self.version(), self.headers().get::<Connection>()) {
(Version::HTTP_10, None) => false,
(Version::HTTP_10, Some(conn))
if !conn.contains(&ConnectionOption::KeepAlive) => false,
(Version::HTTP_11, Some(conn))
if conn.contains(&ConnectionOption::Close) => false,
_ => true
};
trace!("should_keep_alive(version={:?}, header={:?}) = {:?}",
self.version(), self.headers().get::<Connection>(), ret);
ret
}
pub(crate) fn is_upgrade(&self) -> bool {
if let Some(&Connection(ref conn)) = self.headers().get() {
conn.contains(&ConnectionOption::from_str("upgrade").unwrap())
@ -199,7 +214,7 @@ impl Body {
}
}
/// Implements by something that can be converted to `HttpMessage`
/// Implements by something that can be converted to `HttpResponse`
pub trait IntoHttpResponse {
/// Convert into response.
fn response(self, req: HttpRequest) -> HttpResponse;

View File

@ -6,6 +6,7 @@ extern crate time;
extern crate bytes;
extern crate rand;
extern crate sha1;
extern crate url;
#[macro_use]
extern crate futures;
extern crate tokio_core;
@ -14,6 +15,7 @@ extern crate tokio_proto;
#[macro_use]
extern crate hyper;
extern crate unicase;
extern crate http;
extern crate httparse;
extern crate route_recognizer;
@ -37,11 +39,11 @@ mod wsframe;
mod wsproto;
pub mod httpcodes;
pub use application::HttpApplication;
pub use application::Application;
pub use httpmessage::{HttpRequest, HttpResponse, IntoHttpResponse};
pub use router::RoutingMap;
pub use resource::{Reply, Resource};
pub use route::{Route, RouteFactory, RouteHandler, Payload, PayloadItem};
pub use resource::{HttpMessage, HttpResource};
pub use server::HttpServer;
pub use context::HttpContext;
pub use router::RoutingMap;
pub use httpmessage::{HttpRequest, HttpResponse, IntoHttpResponse};
pub use route_recognizer::Params;

View File

@ -21,13 +21,13 @@ impl Route for MyRoute {
fn request(req: HttpRequest,
payload: Option<Payload>,
ctx: &mut HttpContext<Self>) -> HttpMessage<Self>
ctx: &mut HttpContext<Self>) -> Reply<Self>
{
if let Some(pl) = payload {
ctx.add_stream(pl);
HttpMessage::stream(MyRoute{req: Some(req)})
Reply::stream(MyRoute{req: Some(req)})
} else {
HttpMessage::reply_with(req, httpcodes::HTTPOk)
Reply::with(req, httpcodes::HTTPOk)
}
}
}
@ -64,20 +64,20 @@ impl Route for MyWS {
fn request(req: HttpRequest,
payload: Option<Payload>,
ctx: &mut HttpContext<Self>) -> HttpMessage<Self>
ctx: &mut HttpContext<Self>) -> Reply<Self>
{
if let Some(payload) = payload {
match ws::handshake(req) {
Ok(resp) => {
ctx.start(resp);
ctx.add_stream(ws::WsStream::new(payload));
HttpMessage::stream(MyWS{})
Reply::stream(MyWS{})
},
Err(err) =>
HttpMessage::reply(err)
Reply::reply(err)
}
} else {
HttpMessage::reply_with(req, httpcodes::HTTPBadRequest)
Reply::with(req, httpcodes::HTTPBadRequest)
}
}
}
@ -112,7 +112,7 @@ fn main() {
let mut routes = RoutingMap::default();
let mut app = HttpApplication::no_state();
let mut app = Application::default();
app.add("/test")
.get::<MyRoute>()
.post::<MyRoute>();

View File

@ -13,7 +13,7 @@ use httpmessage::{HttpRequest, HttpResponse, IntoHttpResponse};
/// Http resource
///
/// `HttpResource` is an entry in route table which corresponds to requested URL.
/// `Resource` is an entry in route table which corresponds to requested URL.
///
/// Resource in turn has at least one route.
/// Route corresponds to handling HTTP method by calling route handler.
@ -29,15 +29,15 @@ use httpmessage::{HttpRequest, HttpResponse, IntoHttpResponse};
/// .add_resource("/")
/// .post::<MyRoute>();
/// }
pub struct HttpResource<S=()> {
pub struct Resource<S=()> {
state: PhantomData<S>,
routes: HashMap<Method, Box<RouteHandler<S>>>,
default: Box<RouteHandler<S>>,
}
impl<S> Default for HttpResource<S> {
impl<S> Default for Resource<S> {
fn default() -> Self {
HttpResource {
Resource {
state: PhantomData,
routes: HashMap::new(),
default: Box::new(HTTPMethodNotAllowed)}
@ -45,7 +45,7 @@ impl<S> Default for HttpResource<S> {
}
impl<S> HttpResource<S> where S: 'static {
impl<S> Resource<S> where S: 'static {
/// Register handler for specified method.
pub fn handler<H>(&mut self, method: Method, handler: H) -> &mut Self
@ -90,7 +90,7 @@ impl<S> HttpResource<S> where S: 'static {
}
impl<S: 'static> RouteHandler<S> for HttpResource<S> {
impl<S: 'static> RouteHandler<S> for Resource<S> {
fn handle(&self, req: HttpRequest, payload: Option<Payload>, state: Rc<S>) -> Task {
if let Some(handler) = self.routes.get(req.method()) {
@ -103,37 +103,37 @@ impl<S: 'static> RouteHandler<S> for HttpResource<S> {
#[cfg_attr(feature="cargo-clippy", allow(large_enum_variant))]
enum HttpMessageItem<A> where A: Actor<Context=HttpContext<A>> + Route {
enum ReplyItem<A> where A: Actor<Context=HttpContext<A>> + Route {
Message(HttpResponse),
Actor(A),
}
/// Represents response process.
pub struct HttpMessage<A: Actor<Context=HttpContext<A>> + Route> (HttpMessageItem<A>);
pub struct Reply<A: Actor<Context=HttpContext<A>> + Route> (ReplyItem<A>);
impl<A> HttpMessage<A> where A: Actor<Context=HttpContext<A>> + Route
impl<A> Reply<A> where A: Actor<Context=HttpContext<A>> + Route
{
/// Create async response
pub fn stream(act: A) -> Self {
HttpMessage(HttpMessageItem::Actor(act))
Reply(ReplyItem::Actor(act))
}
/// Send response
pub fn reply(msg: HttpResponse) -> Self {
HttpMessage(HttpMessageItem::Message(msg))
Reply(ReplyItem::Message(msg))
}
/// Send response
pub fn reply_with<I: IntoHttpResponse>(req: HttpRequest, msg: I) -> Self {
HttpMessage(HttpMessageItem::Message(msg.response(req)))
pub fn with<I: IntoHttpResponse>(req: HttpRequest, msg: I) -> Self {
Reply(ReplyItem::Message(msg.response(req)))
}
pub(crate) fn into(self, mut ctx: HttpContext<A>) -> Task {
match self.0 {
HttpMessageItem::Message(msg) => {
ReplyItem::Message(msg) => {
Task::reply(msg)
},
HttpMessageItem::Actor(act) => {
ReplyItem::Actor(act) => {
ctx.set_actor(act);
Task::with_stream(ctx)
}

View File

@ -7,7 +7,7 @@ use futures::unsync::mpsc::Receiver;
use task::Task;
use context::HttpContext;
use resource::HttpMessage;
use resource::Reply;
use httpmessage::{HttpRequest, HttpResponse};
/// Stream of `PayloadItem`'s
@ -45,7 +45,7 @@ pub enum Frame {
Payload(Option<Bytes>),
}
/// Trait defines object that could be regestered as resource route.
/// Trait defines object that could be regestered as resource route
pub trait RouteHandler<S>: 'static {
fn handle(&self, req: HttpRequest, payload: Option<Payload>, state: Rc<S>) -> Task;
}
@ -57,12 +57,12 @@ pub trait Route: Actor<Context=HttpContext<Self>> {
type State;
/// Handle incoming request. Route actor can return
/// result immediately with `HttpMessage::reply` or `HttpMessage::error`.
/// result immediately with `Reply::reply` or `Reply::with`.
/// Actor itself could be returned for handling streaming request/response.
/// In that case `HttpContext::start` and `HttpContext::write` hs to be used.
/// In that case `HttpContext::start` and `HttpContext::write` has to be used.
fn request(req: HttpRequest,
payload: Option<Payload>,
ctx: &mut HttpContext<Self>) -> HttpMessage<Self>;
ctx: &mut HttpContext<Self>) -> Reply<Self>;
/// This method creates `RouteFactory` for this actor.
fn factory() -> RouteFactory<Self, Self::State> {
@ -70,7 +70,7 @@ pub trait Route: Actor<Context=HttpContext<Self>> {
}
}
/// This is used for routes registration within `HttpResource`.
/// This is used for routes registration within `Resource`
pub struct RouteFactory<A: Route<State=S>, S>(PhantomData<A>);
impl<A, S> RouteHandler<S> for RouteFactory<A, S>

View File

@ -5,12 +5,12 @@ use route_recognizer::{Router as Recognizer};
use task::Task;
use route::{Payload, RouteHandler};
use resource::HttpResource;
use application::HttpApplication;
use resource::Resource;
use application::Application;
use httpcodes::HTTPNotFound;
use httpmessage::{HttpRequest, IntoHttpResponse};
pub trait HttpHandler: 'static {
pub(crate) trait Handler: 'static {
fn handle(&self, req: HttpRequest, payload: Option<Payload>) -> Task;
}
@ -29,8 +29,8 @@ pub trait HttpHandler: 'static {
/// router.add_resource("/users/:userid/:friendid").get::<MyRoute>();
/// ```
pub struct RoutingMap {
apps: HashMap<String, Box<HttpHandler>>,
resources: HashMap<String, HttpResource>,
apps: HashMap<String, Box<Handler>>,
resources: HashMap<String, Resource>,
}
impl Default for RoutingMap {
@ -44,7 +44,7 @@ impl Default for RoutingMap {
impl RoutingMap {
/// Add `HttpApplication` object with specific prefix.
/// Add `Application` object with specific prefix.
/// Application prefixes all registered resources with specified prefix.
///
/// ```rust,ignore
@ -52,7 +52,7 @@ impl RoutingMap {
/// struct MyRoute;
///
/// fn main() {
/// let mut app = HttpApplication::no_state();
/// let mut app = Application::default();
/// app.add("/test")
/// .get::<MyRoute>()
/// .post::<MyRoute>();
@ -62,7 +62,7 @@ impl RoutingMap {
/// }
/// ```
/// In this example, `MyRoute` route is available as `http://.../pre/test` url.
pub fn add<P, S: 'static>(&mut self, prefix: P, app: HttpApplication<S>)
pub fn add<P, S: 'static>(&mut self, prefix: P, app: Application<S>)
where P: ToString
{
let prefix = prefix.to_string();
@ -76,7 +76,7 @@ impl RoutingMap {
self.apps.insert(prefix.clone(), app.prepare(prefix));
}
/// This method creates `HttpResource` for specified path
/// This method creates `Resource` for specified path
/// or returns mutable reference to resource object.
///
/// ```rust,ignore
@ -91,14 +91,14 @@ impl RoutingMap {
/// }
/// ```
/// In this example, `MyRoute` route is available as `http://.../test` url.
pub fn add_resource<P>(&mut self, path: P) -> &mut HttpResource
pub fn add_resource<P>(&mut self, path: P) -> &mut Resource
where P: ToString
{
let path = path.to_string();
// add resource
if !self.resources.contains_key(&path) {
self.resources.insert(path.clone(), HttpResource::default());
self.resources.insert(path.clone(), Resource::default());
}
self.resources.get_mut(&path).unwrap()
@ -121,8 +121,8 @@ impl RoutingMap {
pub(crate)
struct Router {
apps: HashMap<String, Box<HttpHandler>>,
resources: Recognizer<HttpResource>,
apps: HashMap<String, Box<Handler>>,
resources: Recognizer<Resource>,
}
impl Router {

View File

@ -10,7 +10,7 @@ use task::Task;
use reader::Reader;
use router::{Router, RoutingMap};
/// An HTTP Server.
/// An HTTP Server
pub struct HttpServer {
router: Rc<Router>,
}

View File

@ -22,7 +22,7 @@
//! type State = ();
//!
//! fn request(req: HttpRequest, payload: Option<Payload>,
//! ctx: &mut HttpContext<Self>) -> HttpMessage<Self>
//! ctx: &mut HttpContext<Self>) -> Reply<Self>
//! {
//! if let Some(payload) = payload {
//! // WebSocket handshake
@ -33,13 +33,13 @@
//! // Map Payload into WsStream
//! ctx.add_stream(ws::WsStream::new(payload));
//! // Start ws messages processing
//! HttpMessage::stream(WsRoute)
//! Reply::stream(WsRoute)
//! },
//! Err(err) =>
//! HttpMessage::reply(err)
//! Reply::reply(err)
//! }
//! } else {
//! HttpMessage::reply_with(req, httpcodes::HTTPBadRequest)
//! Reply::with(req, httpcodes::HTTPBadRequest)
//! }
//! }
//! }