Compare commits

..

2 Commits

Author SHA1 Message Date
rmanach
0e61657090 fix documentation + update README 2023-02-16 15:24:28 +01:00
72bf34127b add get status code method in http response 2023-02-16 10:40:29 +00:00
8 changed files with 51 additions and 16 deletions

View File

@ -1,6 +1,6 @@
[package] [package]
name = "http" name = "http"
version = "0.1.4" version = "0.1.6"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

View File

@ -1,3 +1,27 @@
# http # http
A basic Rust lib to parse an HTTP request and build HTTP response. A basic Rust library to parse an HTTP request and build HTTP response.
**NOTE**: only few parts of the specification has been implemented and only JSON body are allowed.
## Integration
Get the latest version:
```toml
http = { git = "https://gitea.thegux.fr/rmanach/http" }
```
Or get a specific version:
```toml
http = { git = "https://gitea.thegux.fr/rmanach/http", version = "0.1.2" }
```
## Documentation
```bash
cargo doc -r --no-deps --open
```
## Launch unit tests
```bash
cargo test
```

View File

@ -7,8 +7,8 @@ pub struct HTTPBody {
data: JsonValue, data: JsonValue,
} }
/// HTTPBody represents an HTTP request body /// HTTPBody represents an HTTP request body.
/// for simplicity, only JSON body is allowed /// For simplicity, only JSON body is allowed.
impl HTTPBody { impl HTTPBody {
fn new(data: JsonValue) -> HTTPBody { fn new(data: JsonValue) -> HTTPBody {
HTTPBody { data } HTTPBody { data }

View File

@ -1,10 +1,12 @@
//! http parses the request according to the HTTP message specifications //! **http** library is a light HTTP parser and builder.
//! it also includes `HTTPResponse` to build an HTTPResponse
//! //!
//! see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages //! It parses the request according to the HTTP message specifications and includes `HTTPResponse` to build an HTTP Response.
//! NOTE: only few parts of the specification has been implemented
//! //!
//! * Only json body allowed //! See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages> for more details.
//!
//! NOTE: only few parts of the specification has been implemented.
//!
//! * Only JSON body allowed
//! * HTTP Headers not parsed //! * HTTP Headers not parsed
mod body; mod body;

View File

@ -36,7 +36,7 @@ impl JSONMessage {
self.message.insert(key.to_string(), value.to_string()); self.message.insert(key.to_string(), value.to_string());
} }
/// associated function to build an HTTPMessage error // associated function to build an HTTPMessage error
pub fn error(message: &str) -> Option<JsonValue> { pub fn error(message: &str) -> Option<JsonValue> {
let mut http_message = JSONMessage::default(); let mut http_message = JSONMessage::default();
http_message.put("error", message); http_message.put("error", message);
@ -54,7 +54,7 @@ impl JSONMessage {
} }
} }
/// loops over all the HashMap keys, builds a JSON key value for each one and join them with `JSON_DELIMITER` /// build_json loops over all the HashMap keys, builds a JSON key value for each one and join them with `JSON_DELIMITER`
fn build_json(self) -> String { fn build_json(self) -> String {
let unstruct: Vec<String> = self let unstruct: Vec<String> = self
.message .message

View File

@ -16,14 +16,14 @@ pub struct HTTPRequest<'a> {
impl<'a> HTTPRequest<'a> { impl<'a> HTTPRequest<'a> {
/// get_request_parts splits correctly the incoming request in order to get: /// get_request_parts splits correctly the incoming request in order to get:
/// * start_line /// * start line
/// * headers /// * headers
/// * data (if exists) /// * data (if exists)
fn get_request_parts(request: &str) -> Result<RequestParts, &str> { fn get_request_parts(request: &str) -> Result<RequestParts, &str> {
let mut request_parts: VecDeque<&str> = request.split(HTTP_REQUEST_SEPARATOR).collect(); let mut request_parts: VecDeque<&str> = request.split(HTTP_REQUEST_SEPARATOR).collect();
if request_parts.len() < 3 { if request_parts.len() < 3 {
return Err("request has no enough informations to be correctly parsed"); return Err("request has not enough informations to be correctly parsed");
} }
let start_line = request_parts.pop_front().unwrap(); let start_line = request_parts.pop_front().unwrap();
@ -55,7 +55,7 @@ impl<'a> HTTPRequest<'a> {
} }
} }
/// get_bodyèvalue retrieves JSON value in `HTTPBody` /// get_body_value retrieves JSON value in `HTTPBody`
pub fn get_body_value(&self, key: &str) -> Option<String> { pub fn get_body_value(&self, key: &str) -> Option<String> {
match self.body { match self.body {
Some(ref b) => match &b.get_data() { Some(ref b) => match &b.get_data() {

View File

@ -10,6 +10,7 @@ const BAD_REQUEST_ERROR: &'static str = r#"{"error":"bad request"}"#;
const STATUS_OK: &'static str = r#"{"status":"ok"}"#; const STATUS_OK: &'static str = r#"{"status":"ok"}"#;
/// HTTPResponse represents an HTTP response (headers are not parsed) /// HTTPResponse represents an HTTP response (headers are not parsed)
///
/// NOTE: for simplicity, only JSON body are allowed /// NOTE: for simplicity, only JSON body are allowed
pub struct HTTPResponse { pub struct HTTPResponse {
status_line: HTTPStatusLine, status_line: HTTPStatusLine,
@ -33,12 +34,16 @@ impl Default for HTTPResponse {
fn default() -> Self { fn default() -> Self {
HTTPResponse { HTTPResponse {
status_line: HTTPStatusLine::default(), status_line: HTTPStatusLine::default(),
body: json::parse(r#"{}"#).unwrap(), body: json::parse("{}").unwrap(),
} }
} }
} }
impl HTTPResponse { impl HTTPResponse {
pub fn get_status_code(&self) -> HTTPStatusCode {
self.status_line.get_status_code()
}
pub fn as_500(message: Option<json::JsonValue>) -> Self { pub fn as_500(message: Option<json::JsonValue>) -> Self {
let mut response = Self::default(); let mut response = Self::default();

View File

@ -1,6 +1,6 @@
use crate::HTTPVersion; use crate::HTTPVersion;
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq, Clone, Copy)]
pub enum HTTPStatusCode { pub enum HTTPStatusCode {
Http200, Http200,
Http400, Http400,
@ -44,6 +44,10 @@ impl Into<String> for HTTPStatusLine {
} }
impl HTTPStatusLine { impl HTTPStatusLine {
pub fn get_status_code(&self) -> HTTPStatusCode {
self.status_code
}
pub fn set_status_code(&mut self, code: HTTPStatusCode) { pub fn set_status_code(&mut self, code: HTTPStatusCode) {
self.status_code = code; self.status_code = code;
} }