Skip to content

Commit 486a219

Browse files
committed
Merge pull request #448 from mlalic/http2-initial
feat(client): initial support for HTTP/2
2 parents 0cd7e9d + 6504936 commit 486a219

File tree

11 files changed

+1507
-188
lines changed

11 files changed

+1507
-188
lines changed

Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ unicase = "0.1"
2424
url = "0.2"
2525
traitobject = "0.0.1"
2626
typeable = "0.1"
27+
solicit = "0.2"
2728

2829
[dev-dependencies]
2930
env_logger = "*"

examples/client_http2.rs

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#![deny(warnings)]
2+
extern crate hyper;
3+
4+
extern crate env_logger;
5+
6+
use std::env;
7+
use std::io;
8+
9+
use hyper::Client;
10+
use hyper::header::Connection;
11+
use hyper::http2;
12+
13+
fn main() {
14+
env_logger::init().unwrap();
15+
16+
let url = match env::args().nth(1) {
17+
Some(url) => url,
18+
None => {
19+
println!("Usage: client <url>");
20+
return;
21+
}
22+
};
23+
24+
let mut client = Client::with_protocol(http2::new_protocol());
25+
26+
// `Connection: Close` is not a valid header for HTTP/2, but the client handles it gracefully.
27+
let mut res = client.get(&*url)
28+
.header(Connection::close())
29+
.send().unwrap();
30+
31+
println!("Response: {}", res.status);
32+
println!("Headers:\n{}", res.headers);
33+
io::copy(&mut res, &mut io::stdout()).unwrap();
34+
}

src/client/mod.rs

+16-38
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,14 @@ pub mod pool;
5454
pub mod request;
5555
pub mod response;
5656

57+
use message::Protocol;
58+
use http11::Http11Protocol;
59+
5760
/// A Client to use additional features with Requests.
5861
///
5962
/// Clients can handle things such as: redirect policy, connection pooling.
6063
pub struct Client {
61-
connector: Connector,
64+
protocol: Box<Protocol + Send>,
6265
redirect_policy: RedirectPolicy,
6366
}
6467

@@ -77,15 +80,20 @@ impl Client {
7780
/// Create a new client with a specific connector.
7881
pub fn with_connector<C, S>(connector: C) -> Client
7982
where C: NetworkConnector<Stream=S> + Send + 'static, S: NetworkStream + Send {
83+
Client::with_protocol(Http11Protocol::with_connector(connector))
84+
}
85+
86+
/// Create a new client with a specific `Protocol`.
87+
pub fn with_protocol<P: Protocol + Send + 'static>(protocol: P) -> Client {
8088
Client {
81-
connector: with_connector(connector),
89+
protocol: Box::new(protocol),
8290
redirect_policy: Default::default()
8391
}
8492
}
8593

8694
/// Set the SSL verifier callback for use with OpenSSL.
8795
pub fn set_ssl_verifier(&mut self, verifier: ContextVerifier) {
88-
self.connector.set_ssl_verifier(verifier);
96+
self.protocol.set_ssl_verifier(verifier);
8997
}
9098

9199
/// Set the RedirectPolicy.
@@ -131,44 +139,10 @@ impl Client {
131139
}
132140
}
133141

134-
fn with_connector<C: NetworkConnector<Stream=S> + Send + 'static, S: NetworkStream + Send>(c: C) -> Connector {
135-
Connector(Box::new(ConnAdapter(c)))
136-
}
137-
138142
impl Default for Client {
139143
fn default() -> Client { Client::new() }
140144
}
141145

142-
struct ConnAdapter<C: NetworkConnector + Send>(C);
143-
144-
impl<C: NetworkConnector<Stream=S> + Send, S: NetworkStream + Send> NetworkConnector for ConnAdapter<C> {
145-
type Stream = Box<NetworkStream + Send>;
146-
#[inline]
147-
fn connect(&self, host: &str, port: u16, scheme: &str)
148-
-> ::Result<Box<NetworkStream + Send>> {
149-
Ok(try!(self.0.connect(host, port, scheme)).into())
150-
}
151-
#[inline]
152-
fn set_ssl_verifier(&mut self, verifier: ContextVerifier) {
153-
self.0.set_ssl_verifier(verifier);
154-
}
155-
}
156-
157-
struct Connector(Box<NetworkConnector<Stream=Box<NetworkStream + Send>> + Send>);
158-
159-
impl NetworkConnector for Connector {
160-
type Stream = Box<NetworkStream + Send>;
161-
#[inline]
162-
fn connect(&self, host: &str, port: u16, scheme: &str)
163-
-> ::Result<Box<NetworkStream + Send>> {
164-
Ok(try!(self.0.connect(host, port, scheme)).into())
165-
}
166-
#[inline]
167-
fn set_ssl_verifier(&mut self, verifier: ContextVerifier) {
168-
self.0.set_ssl_verifier(verifier);
169-
}
170-
}
171-
172146
/// Options for an individual Request.
173147
///
174148
/// One of these will be built for you if you use one of the convenience
@@ -229,7 +203,11 @@ impl<'a, U: IntoUrl> RequestBuilder<'a, U> {
229203
};
230204

231205
loop {
232-
let mut req = try!(Request::with_connector(method.clone(), url.clone(), &client.connector));
206+
let message = {
207+
let (host, port) = try!(get_host_and_port(&url));
208+
try!(client.protocol.new_message(&host, port, &*url.scheme))
209+
};
210+
let mut req = try!(Request::with_message(method.clone(), url.clone(), message));
233211
headers.as_ref().map(|headers| req.headers_mut().extend(headers.iter()));
234212

235213
match (can_have_body, body.as_ref()) {

src/client/request.rs

+47-87
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
11
//! Client Requests
22
use std::marker::PhantomData;
3-
use std::io::{self, Write, BufWriter};
3+
use std::io::{self, Write};
44

55
use url::Url;
66

77
use method::{self, Method};
88
use header::Headers;
9-
use header::{self, Host};
9+
use header::Host;
1010
use net::{NetworkStream, NetworkConnector, HttpConnector, Fresh, Streaming};
11-
use http::{HttpWriter, LINE_ENDING};
12-
use http::HttpWriter::{ThroughWriter, ChunkedWriter, SizedWriter, EmptyWriter};
1311
use version;
1412
use client::{Response, get_host_and_port};
1513

14+
use message::{HttpMessage, RequestHead};
15+
use http11::Http11Message;
16+
1617

1718
/// A client request to a remote server.
1819
/// The W type tracks the state of the request, Fresh vs Streaming.
@@ -23,7 +24,7 @@ pub struct Request<W> {
2324
/// The HTTP version of this request.
2425
pub version: version::HttpVersion,
2526

26-
body: HttpWriter<BufWriter<Box<NetworkStream + Send>>>,
27+
message: Box<HttpMessage>,
2728
headers: Headers,
2829
method: method::Method,
2930

@@ -41,22 +42,12 @@ impl<W> Request<W> {
4142
}
4243

4344
impl Request<Fresh> {
44-
/// Create a new client request.
45-
pub fn new(method: method::Method, url: Url) -> ::Result<Request<Fresh>> {
46-
let mut conn = HttpConnector(None);
47-
Request::with_connector(method, url, &mut conn)
48-
}
49-
50-
/// Create a new client request with a specific underlying NetworkStream.
51-
pub fn with_connector<C, S>(method: method::Method, url: Url, connector: &C)
52-
-> ::Result<Request<Fresh>> where
53-
C: NetworkConnector<Stream=S>,
54-
S: Into<Box<NetworkStream + Send>> {
45+
/// Create a new `Request<Fresh>` that will use the given `HttpMessage` for its communication
46+
/// with the server. This implies that the given `HttpMessage` instance has already been
47+
/// properly initialized by the caller (e.g. a TCP connection's already established).
48+
pub fn with_message(method: method::Method, url: Url, message: Box<HttpMessage>)
49+
-> ::Result<Request<Fresh>> {
5550
let (host, port) = try!(get_host_and_port(&url));
56-
57-
let stream = try!(connector.connect(&*host, port, &*url.scheme)).into();
58-
let stream = ThroughWriter(BufWriter::new(stream));
59-
6051
let mut headers = Headers::new();
6152
headers.set(Host {
6253
hostname: host,
@@ -68,77 +59,43 @@ impl Request<Fresh> {
6859
headers: headers,
6960
url: url,
7061
version: version::HttpVersion::Http11,
71-
body: stream,
62+
message: message,
7263
_marker: PhantomData,
7364
})
7465
}
7566

76-
/// Consume a Fresh Request, writing the headers and method,
77-
/// returning a Streaming Request.
78-
pub fn start(mut self) -> ::Result<Request<Streaming>> {
79-
let mut uri = self.url.serialize_path().unwrap();
80-
if let Some(ref q) = self.url.query {
81-
uri.push('?');
82-
uri.push_str(&q[..]);
83-
}
84-
85-
debug!("request line: {:?} {:?} {:?}", self.method, uri, self.version);
86-
try!(write!(&mut self.body, "{} {} {}{}",
87-
self.method, uri, self.version, LINE_ENDING));
88-
89-
90-
let stream = match self.method {
91-
Method::Get | Method::Head => {
92-
debug!("headers={:?}", self.headers);
93-
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
94-
EmptyWriter(self.body.into_inner())
95-
},
96-
_ => {
97-
let mut chunked = true;
98-
let mut len = 0;
99-
100-
match self.headers.get::<header::ContentLength>() {
101-
Some(cl) => {
102-
chunked = false;
103-
len = **cl;
104-
},
105-
None => ()
106-
};
107-
108-
// can't do in match above, thanks borrowck
109-
if chunked {
110-
let encodings = match self.headers.get_mut::<header::TransferEncoding>() {
111-
Some(&mut header::TransferEncoding(ref mut encodings)) => {
112-
//TODO: check if chunked is already in encodings. use HashSet?
113-
encodings.push(header::Encoding::Chunked);
114-
false
115-
},
116-
None => true
117-
};
118-
119-
if encodings {
120-
self.headers.set::<header::TransferEncoding>(
121-
header::TransferEncoding(vec![header::Encoding::Chunked]))
122-
}
123-
}
67+
/// Create a new client request.
68+
pub fn new(method: method::Method, url: Url) -> ::Result<Request<Fresh>> {
69+
let mut conn = HttpConnector(None);
70+
Request::with_connector(method, url, &mut conn)
71+
}
12472

125-
debug!("headers={:?}", self.headers);
126-
try!(write!(&mut self.body, "{}{}", self.headers, LINE_ENDING));
73+
/// Create a new client request with a specific underlying NetworkStream.
74+
pub fn with_connector<C, S>(method: method::Method, url: Url, connector: &C)
75+
-> ::Result<Request<Fresh>> where
76+
C: NetworkConnector<Stream=S>,
77+
S: Into<Box<NetworkStream + Send>> {
78+
let (host, port) = try!(get_host_and_port(&url));
79+
let stream = try!(connector.connect(&*host, port, &*url.scheme)).into();
12780

128-
if chunked {
129-
ChunkedWriter(self.body.into_inner())
130-
} else {
131-
SizedWriter(self.body.into_inner(), len)
132-
}
133-
}
134-
};
81+
Request::with_message(method, url, Box::new(Http11Message::with_stream(stream)))
82+
}
13583

136-
Ok(Request {
137-
method: self.method,
84+
/// Consume a Fresh Request, writing the headers and method,
85+
/// returning a Streaming Request.
86+
pub fn start(mut self) -> ::Result<Request<Streaming>> {
87+
let head = try!(self.message.set_outgoing(RequestHead {
13888
headers: self.headers,
89+
method: self.method,
13990
url: self.url,
91+
}));
92+
93+
Ok(Request {
94+
method: head.method,
95+
headers: head.headers,
96+
url: head.url,
14097
version: self.version,
141-
body: stream,
98+
message: self.message,
14299
_marker: PhantomData,
143100
})
144101
}
@@ -153,20 +110,19 @@ impl Request<Streaming> {
153110
///
154111
/// Consumes the Request.
155112
pub fn send(self) -> ::Result<Response> {
156-
let raw = try!(self.body.end()).into_inner().unwrap(); // end() already flushes
157-
Response::new(raw)
113+
Response::with_message(self.message)
158114
}
159115
}
160116

161117
impl Write for Request<Streaming> {
162118
#[inline]
163119
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
164-
self.body.write(msg)
120+
self.message.write(msg)
165121
}
166122

167123
#[inline]
168124
fn flush(&mut self) -> io::Result<()> {
169-
self.body.flush()
125+
self.message.flush()
170126
}
171127
}
172128

@@ -180,11 +136,15 @@ mod tests {
180136
use header::{ContentLength,TransferEncoding,Encoding};
181137
use url::form_urlencoded;
182138
use super::Request;
139+
use http11::Http11Message;
183140

184141
fn run_request(req: Request<Fresh>) -> Vec<u8> {
185142
let req = req.start().unwrap();
186-
let stream = *req.body.end().unwrap()
187-
.into_inner().unwrap().downcast::<MockStream>().ok().unwrap();
143+
let message = req.message;
144+
let mut message = message.downcast::<Http11Message>().ok().unwrap();
145+
message.flush_outgoing().unwrap();
146+
let stream = *message
147+
.into_inner().downcast::<MockStream>().ok().unwrap();
188148
stream.write
189149
}
190150

0 commit comments

Comments
 (0)