From ccb1dce87164e100860006a1d89438335e3821ff Mon Sep 17 00:00:00 2001 From: vodofrede Date: Tue, 27 Feb 2024 23:50:36 +0100 Subject: [PATCH] initial commit --- .gitignore | 6 ++ Cargo.lock | 61 ++++++++++++++++++++ Cargo.toml | 9 +++ LICENSE.txt | 11 ++++ README.md | 3 + src/bin/get.rs | 7 +++ src/lib.rs | 148 +++++++++++++++++++++++++++++++++++++++++++++++++ src/tests.rs | 36 ++++++++++++ 8 files changed, 281 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE.txt create mode 100644 README.md create mode 100644 src/bin/get.rs create mode 100644 src/lib.rs create mode 100644 src/tests.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a5aa4f3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +# temporary files +/target + +# editors +.fleet +.vscode diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..1b0c4ea --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,61 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "aho-corasick" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0" +dependencies = [ + "memchr", +] + +[[package]] +name = "memchr" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149" + +[[package]] +name = "once_cell" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" + +[[package]] +name = "regex" +version = "1.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b62dbe01f0b06f9d8dc7d49e05a0785f153b00b2c227856282f671e0318c9b15" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5bb987efffd3c6d0d8f5f89510bb458559eab11e4f869acb20bf845e016259cd" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" + +[[package]] +name = "request" +version = "0.1.0" +dependencies = [ + "once_cell", + "regex", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..f53a16e --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "request" +version = "0.1.0" +edition = "2021" +authors = ["vodofrede"] + +[dependencies] +once_cell = "1" +regex = "1" diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..a1cbe95 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,11 @@ +Copyright 2024 vodofrede + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..8ca7e9d --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# Request + +A library for making HTTP requests. \ No newline at end of file diff --git a/src/bin/get.rs b/src/bin/get.rs new file mode 100644 index 0000000..803f4ce --- /dev/null +++ b/src/bin/get.rs @@ -0,0 +1,7 @@ +use request::*; + +fn main() { + // create and send a simple request + let response = Request::get("localhost:8000").send().unwrap(); + println!("response: {:#?}", response); +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..0cf78e0 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,148 @@ +#![warn(clippy::all, clippy::pedantic)] +#![deny(unsafe_code)] +#![doc = include_str!("../README.md")] + +#[cfg(test)] +mod tests; + +use once_cell::sync::Lazy; +use regex::Regex; +use std::{ + collections::HashMap, + io::{BufRead, BufReader, Error as IoError, Write}, + net, +}; + +/// An HTTP request. +#[derive(Debug, Clone)] +pub struct Request<'a> { + /// Request URL. + uri: &'a str, + /// An HTTP method. GET by default. + method: Method, + /// Request headers. + headers: HashMap<&'a str, &'a str>, + /// Request body. + body: &'a str, +} + +impl<'a> Request<'a> { + /// Create a new request. + /// + /// Convenience functions are provided for each HTTP method [`Request::get`], [`Request::post`] etc. + pub fn new(uri: &'a str, method: Method) -> Self { + Self { + uri, + method, + headers: HashMap::new(), + body: "", + } + } + + /// Construct a new GET request. + pub fn get(uri: &'a str) -> Self { + Request::new(uri, Method::GET) + } + + /// Construct a new POST request. + pub fn post(uri: &'a str) -> Self { + Request::new(uri, Method::POST) + } + + /// Dispatch the request. + pub fn send(&self) -> Result { + // format the message: Method Request-URI HTTP-Version CRLF headers CRLF message-body + // todo: properly format the headers + let message = format!( + "{:?} {} HTTP/1.1\r\n{:?}\r\n{}\r\n", + self.method, self.uri, self.headers, self.body + ); + + // create the stream + let mut stream = net::TcpStream::connect(self.uri)?; + + // send the message + stream.write(message.as_bytes())?; + + // receive the response + let lines = BufReader::new(stream) + .lines() + .map(|l| l.unwrap()) + .take_while(|l| !l.is_empty()) + .collect::>(); + let received = lines.join("\n"); + + // process response + let response = Response::parse(&received).unwrap(); + + Ok(response) + } +} + +/// HTTP methods. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Method { + GET, + HEAD, + POST, + PUT, + DELETE, + CONNECT, + OPTIONS, + TRACE, + PATCH, +} + +/// An HTTP response. +#[derive(Debug, Clone)] +pub struct Response { + pub version: String, + pub status: u64, + pub reason: String, + pub headers: HashMap, + pub body: Option, +} +impl Response { + pub fn parse(message: &str) -> Result { + // construct a regex: HTTP-Version Status-Code Reason-Phrase CRLF headers CRLF message-body + static REGEX: Lazy = Lazy::new(|| { + Regex::new(r"(?PHTTP/\d\.\d) (?P\d+) (?P[a-zA-Z ]+)(?:\n(?P(?:.+\n)+))?(?:\n(?P(?:.+\n?)+))?").unwrap() + }); + + // parse the response + let Some(parts) = REGEX.captures(message) else { + Err("invalid message")? + }; + let version = parts["version"].to_string(); + let status = parts["status"].parse().unwrap(); + let reason = parts["reason"].to_string(); + + // parse headers + let headers = parts + .name("headers") + .map(|m| m.as_str()) + .unwrap_or("") + .lines() + .map(|l| l.split_once(": ").unwrap()) + .map(|(a, b)| (a.to_string(), b.to_string())) + .collect::>(); + + // parse body + let body = parts.name("body").map(|m| m.as_str().to_string()); + + // construct the response + let response = Response { + version, + status, + reason, + headers, + body, + }; + + Ok(response) + } + + pub fn is_ok(&self) -> bool { + self.status == 200 + } +} diff --git a/src/tests.rs b/src/tests.rs new file mode 100644 index 0000000..056639b --- /dev/null +++ b/src/tests.rs @@ -0,0 +1,36 @@ +use super::*; + +#[test] +fn get() { + common::server(); + + // create and send a simple request + let response = Request::get("localhost:8000").send().unwrap(); + println!("response: {:#?}", response); +} + +#[test] +fn post() {} + +mod common { + use std::{ + io::{BufRead, BufReader, Write}, + net, thread, + }; + + pub fn server() { + let listener = net::TcpListener::bind("localhost:8000").expect("port is in use."); + thread::spawn(move || { + listener + .incoming() + .filter_map(Result::ok) + .for_each(|mut t| { + let _ = BufReader::new(&mut t) + .lines() + .take_while(|l| !l.as_ref().unwrap().is_empty()) + .collect::>(); + t.write(b"HTTP/1.1 200 OK\r\n\r\n").unwrap(); + }) + }); + } +}