1 //! Simple HTTP implementation which supports both async and traditional execution environments
2 //! with minimal dependencies. This is used as the basis for REST and RPC clients.
7 use std::convert::TryFrom;
8 #[cfg(not(feature = "tokio"))]
10 use std::net::ToSocketAddrs;
11 use std::time::Duration;
13 #[cfg(feature = "tokio")]
14 use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
15 #[cfg(feature = "tokio")]
16 use tokio::net::TcpStream;
18 #[cfg(not(feature = "tokio"))]
21 #[cfg(not(feature = "tokio"))]
22 use std::net::TcpStream;
24 /// Timeout for operations on TCP streams.
25 const TCP_STREAM_TIMEOUT: Duration = Duration::from_secs(5);
27 /// Timeout for reading the first byte of a response. This is separate from the general read
28 /// timeout as it is not uncommon for Bitcoin Core to be blocked waiting on UTXO cache flushes for
29 /// upwards of a minute or more. Note that we always retry once when we time out, so the maximum
30 /// time we allow Bitcoin Core to block for is twice this value.
31 const TCP_STREAM_RESPONSE_TIMEOUT: Duration = Duration::from_secs(120);
33 /// Maximum HTTP message header size in bytes.
34 const MAX_HTTP_MESSAGE_HEADER_SIZE: usize = 8192;
36 /// Maximum HTTP message body size in bytes. Enough for a hex-encoded block in JSON format and any
37 /// overhead for HTTP chunked transfer encoding.
38 const MAX_HTTP_MESSAGE_BODY_SIZE: usize = 2 * 4_000_000 + 32_000;
40 /// Endpoint for interacting with an HTTP-based API.
42 pub struct HttpEndpoint {
49 /// Creates an endpoint for the given host and default HTTP port.
50 pub fn for_host(host: String) -> Self {
54 path: String::from("/"),
58 /// Specifies a port to use with the endpoint.
59 pub fn with_port(mut self, port: u16) -> Self {
60 self.port = Some(port);
64 /// Specifies a path to use with the endpoint.
65 pub fn with_path(mut self, path: String) -> Self {
70 /// Returns the endpoint host.
71 pub fn host(&self) -> &str {
75 /// Returns the endpoint port.
76 pub fn port(&self) -> u16 {
83 /// Returns the endpoint path.
84 pub fn path(&self) -> &str {
89 impl<'a> std::net::ToSocketAddrs for &'a HttpEndpoint {
90 type Iter = <(&'a str, u16) as std::net::ToSocketAddrs>::Iter;
92 fn to_socket_addrs(&self) -> std::io::Result<Self::Iter> {
93 (self.host(), self.port()).to_socket_addrs()
97 /// Client for making HTTP requests.
98 pub(crate) struct HttpClient {
103 /// Opens a connection to an HTTP endpoint.
104 pub fn connect<E: ToSocketAddrs>(endpoint: E) -> std::io::Result<Self> {
105 let address = match endpoint.to_socket_addrs()?.next() {
107 return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "could not resolve to any addresses"));
109 Some(address) => address,
111 let stream = std::net::TcpStream::connect_timeout(&address, TCP_STREAM_TIMEOUT)?;
112 stream.set_read_timeout(Some(TCP_STREAM_TIMEOUT))?;
113 stream.set_write_timeout(Some(TCP_STREAM_TIMEOUT))?;
115 #[cfg(feature = "tokio")]
117 stream.set_nonblocking(true)?;
118 TcpStream::from_std(stream)?
124 /// Sends a `GET` request for a resource identified by `uri` at the `host`.
126 /// Returns the response body in `F` format.
128 pub async fn get<F>(&mut self, uri: &str, host: &str) -> std::io::Result<F>
129 where F: TryFrom<Vec<u8>, Error = std::io::Error> {
130 let request = format!(
131 "GET {} HTTP/1.1\r\n\
133 Connection: keep-alive\r\n\
135 let response_body = self.send_request_with_retry(&request).await?;
136 F::try_from(response_body)
139 /// Sends a `POST` request for a resource identified by `uri` at the `host` using the given HTTP
140 /// authentication credentials.
142 /// The request body consists of the provided JSON `content`. Returns the response body in `F`
145 pub async fn post<F>(&mut self, uri: &str, host: &str, auth: &str, content: serde_json::Value) -> std::io::Result<F>
146 where F: TryFrom<Vec<u8>, Error = std::io::Error> {
147 let content = content.to_string();
148 let request = format!(
149 "POST {} HTTP/1.1\r\n\
151 Authorization: {}\r\n\
152 Connection: keep-alive\r\n\
153 Content-Type: application/json\r\n\
154 Content-Length: {}\r\n\
156 {}", uri, host, auth, content.len(), content);
157 let response_body = self.send_request_with_retry(&request).await?;
158 F::try_from(response_body)
161 /// Sends an HTTP request message and reads the response, returning its body. Attempts to
162 /// reconnect and retry if the connection has been closed.
163 async fn send_request_with_retry(&mut self, request: &str) -> std::io::Result<Vec<u8>> {
164 let endpoint = self.stream.peer_addr().unwrap();
165 match self.send_request(request).await {
166 Ok(bytes) => Ok(bytes),
168 // Reconnect and retry on fail. This can happen if the connection was closed after
169 // the keep-alive limits are reached, or generally if the request timed out due to
170 // Bitcoin Core being stuck on a long-running operation or its RPC queue being
172 // Block 100ms before retrying the request as in many cases the source of the error
173 // may be persistent for some time.
174 #[cfg(feature = "tokio")]
175 tokio::time::sleep(Duration::from_millis(100)).await;
176 #[cfg(not(feature = "tokio"))]
177 std::thread::sleep(Duration::from_millis(100));
178 *self = Self::connect(endpoint)?;
179 self.send_request(request).await
184 /// Sends an HTTP request message and reads the response, returning its body.
185 async fn send_request(&mut self, request: &str) -> std::io::Result<Vec<u8>> {
186 self.write_request(request).await?;
187 self.read_response().await
190 /// Writes an HTTP request message.
191 async fn write_request(&mut self, request: &str) -> std::io::Result<()> {
192 #[cfg(feature = "tokio")]
194 self.stream.write_all(request.as_bytes()).await?;
195 self.stream.flush().await
197 #[cfg(not(feature = "tokio"))]
199 self.stream.write_all(request.as_bytes())?;
204 /// Reads an HTTP response message.
205 async fn read_response(&mut self) -> std::io::Result<Vec<u8>> {
206 #[cfg(feature = "tokio")]
207 let stream = self.stream.split().0;
208 #[cfg(not(feature = "tokio"))]
209 let stream = std::io::Read::by_ref(&mut self.stream);
211 let limited_stream = stream.take(MAX_HTTP_MESSAGE_HEADER_SIZE as u64);
213 #[cfg(feature = "tokio")]
214 let mut reader = tokio::io::BufReader::new(limited_stream);
215 #[cfg(not(feature = "tokio"))]
216 let mut reader = std::io::BufReader::new(limited_stream);
218 macro_rules! read_line {
219 () => { read_line!(0) };
220 ($retry_count: expr) => { {
221 let mut line = String::new();
222 let mut timeout_count: u64 = 0;
223 let bytes_read = loop {
224 #[cfg(feature = "tokio")]
225 let read_res = reader.read_line(&mut line).await;
226 #[cfg(not(feature = "tokio"))]
227 let read_res = reader.read_line(&mut line);
229 Ok(bytes_read) => break bytes_read,
230 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
232 if timeout_count > $retry_count {
238 Err(e) => return Err(e),
245 // Remove trailing CRLF
246 if line.ends_with('\n') { line.pop(); if line.ends_with('\r') { line.pop(); } }
253 // Read and parse status line
254 // Note that we allow retrying a few times to reach TCP_STREAM_RESPONSE_TIMEOUT.
255 let status_line = read_line!(TCP_STREAM_RESPONSE_TIMEOUT.as_secs() / TCP_STREAM_TIMEOUT.as_secs())
256 .ok_or(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "no status line"))?;
257 let status = HttpStatus::parse(&status_line)?;
259 // Read and parse relevant headers
260 let mut message_length = HttpMessageLength::Empty;
262 let line = read_line!()
263 .ok_or(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "no headers"))?;
264 if line.is_empty() { break; }
266 let header = HttpHeader::parse(&line)?;
267 if header.has_name("Content-Length") {
268 let length = header.value.parse()
269 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
270 if let HttpMessageLength::Empty = message_length {
271 message_length = HttpMessageLength::ContentLength(length);
276 if header.has_name("Transfer-Encoding") {
277 message_length = HttpMessageLength::TransferEncoding(header.value.into());
283 let read_limit = MAX_HTTP_MESSAGE_BODY_SIZE - reader.buffer().len();
284 reader.get_mut().set_limit(read_limit as u64);
285 let contents = match message_length {
286 HttpMessageLength::Empty => { Vec::new() },
287 HttpMessageLength::ContentLength(length) => {
288 if length == 0 || length > MAX_HTTP_MESSAGE_BODY_SIZE {
289 return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "out of range"))
291 let mut content = vec![0; length];
292 #[cfg(feature = "tokio")]
293 reader.read_exact(&mut content[..]).await?;
294 #[cfg(not(feature = "tokio"))]
295 reader.read_exact(&mut content[..])?;
299 HttpMessageLength::TransferEncoding(coding) => {
300 if !coding.eq_ignore_ascii_case("chunked") {
301 return Err(std::io::Error::new(
302 std::io::ErrorKind::InvalidInput, "unsupported transfer coding"))
304 let mut content = Vec::new();
305 #[cfg(feature = "tokio")]
307 // Since chunked_transfer doesn't have an async interface, only use it to
308 // determine the size of each chunk to read.
310 // TODO: Replace with an async interface when available.
311 // https://github.com/frewsxcv/rust-chunked-transfer/issues/7
313 // Read the chunk header which contains the chunk size.
314 let mut chunk_header = String::new();
315 reader.read_line(&mut chunk_header).await?;
316 if chunk_header == "0\r\n" {
317 // Read the terminator chunk since the decoder consumes the CRLF
318 // immediately when this chunk is encountered.
319 reader.read_line(&mut chunk_header).await?;
322 // Decode the chunk header to obtain the chunk size.
323 let mut buffer = Vec::new();
324 let mut decoder = chunked_transfer::Decoder::new(chunk_header.as_bytes());
325 decoder.read_to_end(&mut buffer)?;
327 // Read the chunk body.
328 let chunk_size = match decoder.remaining_chunks_size() {
330 Some(chunk_size) => chunk_size,
332 let chunk_offset = content.len();
333 content.resize(chunk_offset + chunk_size + "\r\n".len(), 0);
334 reader.read_exact(&mut content[chunk_offset..]).await?;
335 content.resize(chunk_offset + chunk_size, 0);
339 #[cfg(not(feature = "tokio"))]
341 let mut decoder = chunked_transfer::Decoder::new(reader);
342 decoder.read_to_end(&mut content)?;
350 // TODO: Handle 3xx redirection responses.
351 let error_details = match contents.is_ascii() {
352 true => String::from_utf8_lossy(&contents).to_string(),
353 false => "binary".to_string()
355 let error_msg = format!("Errored with status: {} and contents: {}",
356 status.code, error_details);
357 return Err(std::io::Error::new(std::io::ErrorKind::Other, error_msg));
364 /// HTTP response status code as defined by [RFC 7231].
366 /// [RFC 7231]: https://tools.ietf.org/html/rfc7231#section-6
367 struct HttpStatus<'a> {
371 impl<'a> HttpStatus<'a> {
372 /// Parses an HTTP status line as defined by [RFC 7230].
374 /// [RFC 7230]: https://tools.ietf.org/html/rfc7230#section-3.1.2
375 fn parse(line: &'a String) -> std::io::Result<HttpStatus<'a>> {
376 let mut tokens = line.splitn(3, ' ');
378 let http_version = tokens.next()
379 .ok_or(std::io::Error::new(std::io::ErrorKind::InvalidData, "no HTTP-Version"))?;
380 if !http_version.eq_ignore_ascii_case("HTTP/1.1") &&
381 !http_version.eq_ignore_ascii_case("HTTP/1.0") {
382 return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid HTTP-Version"));
385 let code = tokens.next()
386 .ok_or(std::io::Error::new(std::io::ErrorKind::InvalidData, "no Status-Code"))?;
387 if code.len() != 3 || !code.chars().all(|c| c.is_ascii_digit()) {
388 return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "invalid Status-Code"));
391 let _reason = tokens.next()
392 .ok_or(std::io::Error::new(std::io::ErrorKind::InvalidData, "no Reason-Phrase"))?;
397 /// Returns whether the status is successful (i.e., 2xx status class).
398 fn is_ok(&self) -> bool {
399 self.code.starts_with('2')
403 /// HTTP response header as defined by [RFC 7231].
405 /// [RFC 7231]: https://tools.ietf.org/html/rfc7231#section-7
406 struct HttpHeader<'a> {
411 impl<'a> HttpHeader<'a> {
412 /// Parses an HTTP header field as defined by [RFC 7230].
414 /// [RFC 7230]: https://tools.ietf.org/html/rfc7230#section-3.2
415 fn parse(line: &'a String) -> std::io::Result<HttpHeader<'a>> {
416 let mut tokens = line.splitn(2, ':');
417 let name = tokens.next()
418 .ok_or(std::io::Error::new(std::io::ErrorKind::InvalidData, "no header name"))?;
419 let value = tokens.next()
420 .ok_or(std::io::Error::new(std::io::ErrorKind::InvalidData, "no header value"))?
422 Ok(Self { name, value })
425 /// Returns whether the header field has the given name.
426 fn has_name(&self, name: &str) -> bool {
427 self.name.eq_ignore_ascii_case(name)
431 /// HTTP message body length as defined by [RFC 7230].
433 /// [RFC 7230]: https://tools.ietf.org/html/rfc7230#section-3.3.3
434 enum HttpMessageLength {
436 ContentLength(usize),
437 TransferEncoding(String),
440 /// An HTTP response body in binary format.
441 pub struct BinaryResponse(pub Vec<u8>);
443 /// An HTTP response body in JSON format.
444 pub struct JsonResponse(pub serde_json::Value);
446 /// Interprets bytes from an HTTP response body as binary data.
447 impl TryFrom<Vec<u8>> for BinaryResponse {
448 type Error = std::io::Error;
450 fn try_from(bytes: Vec<u8>) -> std::io::Result<Self> {
451 Ok(BinaryResponse(bytes))
455 /// Interprets bytes from an HTTP response body as a JSON value.
456 impl TryFrom<Vec<u8>> for JsonResponse {
457 type Error = std::io::Error;
459 fn try_from(bytes: Vec<u8>) -> std::io::Result<Self> {
460 Ok(JsonResponse(serde_json::from_slice(&bytes)?))
466 use super::HttpEndpoint;
469 fn with_default_port() {
470 let endpoint = HttpEndpoint::for_host("foo.com".into());
471 assert_eq!(endpoint.host(), "foo.com");
472 assert_eq!(endpoint.port(), 80);
476 fn with_custom_port() {
477 let endpoint = HttpEndpoint::for_host("foo.com".into()).with_port(8080);
478 assert_eq!(endpoint.host(), "foo.com");
479 assert_eq!(endpoint.port(), 8080);
484 let endpoint = HttpEndpoint::for_host("foo.com".into()).with_path("/path".into());
485 assert_eq!(endpoint.host(), "foo.com");
486 assert_eq!(endpoint.path(), "/path");
490 fn without_uri_path() {
491 let endpoint = HttpEndpoint::for_host("foo.com".into());
492 assert_eq!(endpoint.host(), "foo.com");
493 assert_eq!(endpoint.path(), "/");
497 fn convert_to_socket_addrs() {
498 let endpoint = HttpEndpoint::for_host("foo.com".into());
499 let host = endpoint.host();
500 let port = endpoint.port();
502 use std::net::ToSocketAddrs;
503 match (&endpoint).to_socket_addrs() {
504 Err(e) => panic!("Unexpected error: {:?}", e),
505 Ok(mut socket_addrs) => {
506 match socket_addrs.next() {
507 None => panic!("Expected socket address"),
509 assert_eq!(addr, (host, port).to_socket_addrs().unwrap().next().unwrap());
510 assert!(socket_addrs.next().is_none());
519 pub(crate) mod client_tests {
521 use std::io::BufRead;
524 /// Server for handling HTTP client requests with a stock response.
525 pub struct HttpServer {
526 address: std::net::SocketAddr,
527 handler: std::thread::JoinHandle<()>,
528 shutdown: std::sync::Arc<std::sync::atomic::AtomicBool>,
531 /// Body of HTTP response messages.
532 pub enum MessageBody<T: ToString> {
539 pub fn responding_with_ok<T: ToString>(body: MessageBody<T>) -> Self {
540 let response = match body {
541 MessageBody::Empty => "HTTP/1.1 200 OK\r\n\r\n".to_string(),
542 MessageBody::Content(body) => {
543 let body = body.to_string();
545 "HTTP/1.1 200 OK\r\n\
546 Content-Length: {}\r\n\
548 {}", body.len(), body)
550 MessageBody::ChunkedContent(body) => {
551 let mut chuncked_body = Vec::new();
553 use chunked_transfer::Encoder;
554 let mut encoder = Encoder::with_chunks_size(&mut chuncked_body, 8);
555 encoder.write_all(body.to_string().as_bytes()).unwrap();
558 "HTTP/1.1 200 OK\r\n\
559 Transfer-Encoding: chunked\r\n\
561 {}", String::from_utf8(chuncked_body).unwrap())
564 HttpServer::responding_with(response)
567 pub fn responding_with_not_found() -> Self {
568 let response = "HTTP/1.1 404 Not Found\r\n\r\n".to_string();
569 HttpServer::responding_with(response)
572 fn responding_with(response: String) -> Self {
573 let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
574 let address = listener.local_addr().unwrap();
576 let shutdown = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
577 let shutdown_signaled = std::sync::Arc::clone(&shutdown);
578 let handler = std::thread::spawn(move || {
579 for stream in listener.incoming() {
580 let mut stream = stream.unwrap();
581 stream.set_write_timeout(Some(TCP_STREAM_TIMEOUT)).unwrap();
583 let lines_read = std::io::BufReader::new(&stream)
585 .take_while(|line| !line.as_ref().unwrap().is_empty())
587 if lines_read == 0 { continue; }
589 for chunk in response.as_bytes().chunks(16) {
590 if shutdown_signaled.load(std::sync::atomic::Ordering::SeqCst) {
593 if let Err(_) = stream.write(chunk) { break; }
594 if let Err(_) = stream.flush() { break; }
600 Self { address, handler, shutdown }
604 self.shutdown.store(true, std::sync::atomic::Ordering::SeqCst);
605 self.handler.join().unwrap();
608 pub fn endpoint(&self) -> HttpEndpoint {
609 HttpEndpoint::for_host(self.address.ip().to_string()).with_port(self.address.port())
614 fn connect_to_unresolvable_host() {
615 match HttpClient::connect(("example.invalid", 80)) {
616 Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::Other),
617 Ok(_) => panic!("Expected error"),
622 fn connect_with_no_socket_address() {
623 match HttpClient::connect(&vec![][..]) {
624 Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput),
625 Ok(_) => panic!("Expected error"),
630 fn connect_with_unknown_server() {
631 match HttpClient::connect(("::", 80)) {
632 #[cfg(target_os = "windows")]
633 Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::AddrNotAvailable),
634 #[cfg(not(target_os = "windows"))]
635 Err(e) => assert_eq!(e.kind(), std::io::ErrorKind::ConnectionRefused),
636 Ok(_) => panic!("Expected error"),
641 async fn connect_with_valid_endpoint() {
642 let server = HttpServer::responding_with_ok::<String>(MessageBody::Empty);
644 match HttpClient::connect(&server.endpoint()) {
645 Err(e) => panic!("Unexpected error: {:?}", e),
651 async fn read_empty_message() {
652 let server = HttpServer::responding_with("".to_string());
654 let mut client = HttpClient::connect(&server.endpoint()).unwrap();
655 match client.get::<BinaryResponse>("/foo", "foo.com").await {
657 assert_eq!(e.kind(), std::io::ErrorKind::UnexpectedEof);
658 assert_eq!(e.get_ref().unwrap().to_string(), "no status line");
660 Ok(_) => panic!("Expected error"),
665 async fn read_incomplete_message() {
666 let server = HttpServer::responding_with("HTTP/1.1 200 OK".to_string());
668 let mut client = HttpClient::connect(&server.endpoint()).unwrap();
669 match client.get::<BinaryResponse>("/foo", "foo.com").await {
671 assert_eq!(e.kind(), std::io::ErrorKind::UnexpectedEof);
672 assert_eq!(e.get_ref().unwrap().to_string(), "no headers");
674 Ok(_) => panic!("Expected error"),
679 async fn read_too_large_message_headers() {
680 let response = format!(
681 "HTTP/1.1 302 Found\r\n\
683 \r\n", "Z".repeat(MAX_HTTP_MESSAGE_HEADER_SIZE));
684 let server = HttpServer::responding_with(response);
686 let mut client = HttpClient::connect(&server.endpoint()).unwrap();
687 match client.get::<BinaryResponse>("/foo", "foo.com").await {
689 assert_eq!(e.kind(), std::io::ErrorKind::UnexpectedEof);
690 assert_eq!(e.get_ref().unwrap().to_string(), "no headers");
692 Ok(_) => panic!("Expected error"),
697 async fn read_too_large_message_body() {
698 let body = "Z".repeat(MAX_HTTP_MESSAGE_BODY_SIZE + 1);
699 let server = HttpServer::responding_with_ok::<String>(MessageBody::Content(body));
701 let mut client = HttpClient::connect(&server.endpoint()).unwrap();
702 match client.get::<BinaryResponse>("/foo", "foo.com").await {
704 assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
705 assert_eq!(e.get_ref().unwrap().to_string(), "out of range");
707 Ok(_) => panic!("Expected error"),
713 async fn read_message_with_unsupported_transfer_coding() {
714 let response = String::from(
715 "HTTP/1.1 200 OK\r\n\
716 Transfer-Encoding: gzip\r\n\
719 let server = HttpServer::responding_with(response);
721 let mut client = HttpClient::connect(&server.endpoint()).unwrap();
722 match client.get::<BinaryResponse>("/foo", "foo.com").await {
724 assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput);
725 assert_eq!(e.get_ref().unwrap().to_string(), "unsupported transfer coding");
727 Ok(_) => panic!("Expected error"),
732 async fn read_error() {
733 let response = String::from(
734 "HTTP/1.1 500 Internal Server Error\r\n\
735 Content-Length: 10\r\n\r\ntest error\r\n");
736 let server = HttpServer::responding_with(response);
738 let mut client = HttpClient::connect(&server.endpoint()).unwrap();
739 match client.get::<JsonResponse>("/foo", "foo.com").await {
741 assert_eq!(e.get_ref().unwrap().to_string(), "Errored with status: 500 and contents: test error");
742 assert_eq!(e.kind(), std::io::ErrorKind::Other);
744 Ok(_) => panic!("Expected error"),
749 async fn read_empty_message_body() {
750 let server = HttpServer::responding_with_ok::<String>(MessageBody::Empty);
752 let mut client = HttpClient::connect(&server.endpoint()).unwrap();
753 match client.get::<BinaryResponse>("/foo", "foo.com").await {
754 Err(e) => panic!("Unexpected error: {:?}", e),
755 Ok(bytes) => assert_eq!(bytes.0, Vec::<u8>::new()),
760 async fn read_message_body_with_length() {
761 let body = "foo bar baz qux".repeat(32);
762 let content = MessageBody::Content(body.clone());
763 let server = HttpServer::responding_with_ok::<String>(content);
765 let mut client = HttpClient::connect(&server.endpoint()).unwrap();
766 match client.get::<BinaryResponse>("/foo", "foo.com").await {
767 Err(e) => panic!("Unexpected error: {:?}", e),
768 Ok(bytes) => assert_eq!(bytes.0, body.as_bytes()),
773 async fn read_chunked_message_body() {
774 let body = "foo bar baz qux".repeat(32);
775 let chunked_content = MessageBody::ChunkedContent(body.clone());
776 let server = HttpServer::responding_with_ok::<String>(chunked_content);
778 let mut client = HttpClient::connect(&server.endpoint()).unwrap();
779 match client.get::<BinaryResponse>("/foo", "foo.com").await {
780 Err(e) => panic!("Unexpected error: {:?}", e),
781 Ok(bytes) => assert_eq!(bytes.0, body.as_bytes()),
786 async fn reconnect_closed_connection() {
787 let server = HttpServer::responding_with_ok::<String>(MessageBody::Empty);
789 let mut client = HttpClient::connect(&server.endpoint()).unwrap();
790 assert!(client.get::<BinaryResponse>("/foo", "foo.com").await.is_ok());
791 match client.get::<BinaryResponse>("/foo", "foo.com").await {
792 Err(e) => panic!("Unexpected error: {:?}", e),
793 Ok(bytes) => assert_eq!(bytes.0, Vec::<u8>::new()),
798 fn from_bytes_into_binary_response() {
800 match BinaryResponse::try_from(bytes.to_vec()) {
801 Err(e) => panic!("Unexpected error: {:?}", e),
802 Ok(response) => assert_eq!(&response.0, bytes),
807 fn from_invalid_bytes_into_json_response() {
808 let json = serde_json::json!({ "result": 42 });
809 match JsonResponse::try_from(json.to_string().as_bytes()[..5].to_vec()) {
811 Ok(_) => panic!("Expected error"),
816 fn from_valid_bytes_into_json_response() {
817 let json = serde_json::json!({ "result": 42 });
818 match JsonResponse::try_from(json.to_string().as_bytes().to_vec()) {
819 Err(e) => panic!("Unexpected error: {:?}", e),
820 Ok(response) => assert_eq!(response.0, json),