initial commit

This commit is contained in:
Frederik Palmø 2024-02-27 23:50:36 +01:00
commit ccb1dce871
8 changed files with 281 additions and 0 deletions

6
.gitignore vendored Normal file
View file

@ -0,0 +1,6 @@
# temporary files
/target
# editors
.fleet
.vscode

61
Cargo.lock generated Normal file
View file

@ -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",
]

9
Cargo.toml Normal file
View file

@ -0,0 +1,9 @@
[package]
name = "request"
version = "0.1.0"
edition = "2021"
authors = ["vodofrede"]
[dependencies]
once_cell = "1"
regex = "1"

11
LICENSE.txt Normal file
View file

@ -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.

3
README.md Normal file
View file

@ -0,0 +1,3 @@
# Request
A library for making HTTP requests.

7
src/bin/get.rs Normal file
View file

@ -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);
}

148
src/lib.rs Normal file
View file

@ -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<Response, IoError> {
// 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::<Vec<_>>();
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<String, String>,
pub body: Option<String>,
}
impl Response {
pub fn parse(message: &str) -> Result<Self, &'static str> {
// construct a regex: HTTP-Version Status-Code Reason-Phrase CRLF headers CRLF message-body
static REGEX: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"(?P<version>HTTP/\d\.\d) (?P<status>\d+) (?P<reason>[a-zA-Z ]+)(?:\n(?P<headers>(?:.+\n)+))?(?:\n(?P<body>(?:.+\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::<HashMap<String, String>>();
// 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
}
}

36
src/tests.rs Normal file
View file

@ -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::<Vec<_>>();
t.write(b"HTTP/1.1 200 OK\r\n\r\n").unwrap();
})
});
}
}