Skip to content

Commit af5931a

Browse files
committed
refactor code for improved clarity, consistency, and maintainability.
1 parent 368a884 commit af5931a

9 files changed

Lines changed: 202 additions & 143 deletions

File tree

Makefile

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,26 @@ doc:
5353
.PHONY: lint
5454
lint:
5555
@echo "Running linter..."
56-
@cargo clippy -- -D warnings
56+
@cargo clippy --all-targets -- \
57+
-D warnings \
58+
-D dead_code \
59+
-D unused_imports \
60+
-D unused_variables \
61+
-D unused_assignments \
62+
-D missing_docs \
63+
-D unsafe_code \
64+
-D clippy::all
5765

5866
# Run the linter and fix issues where possible
5967
.PHONY: lint-fix
6068
lint-fix:
6169
@echo "Running linter and fixing issues..."
62-
@cargo clippy --fix -- -D warnings
70+
@cargo clippy --fix --allow-dirty --all-targets -- \
71+
-D warnings \
72+
-D dead_code \
73+
-D unused_imports \
74+
-D unused_variables \
75+
-D unused_assignments \
76+
-D missing_docs \
77+
-D unsafe_code \
78+
-D clippy::all

examples/http_server.rs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ use microhttp_rs::{
55
};
66
use serde::{Deserialize, Serialize};
77
use log::{info};
8-
use env_logger;
98

109
#[tokio::main]
1110
async fn main() -> Result<(), Box<dyn std::error::Error>> {
@@ -37,7 +36,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
3736

3837
Ok(HttpResponse::new(StatusCode::Ok)
3938
.with_content_type("text/plain")
40-
.with_body_string(format!("Hello, {}!", name)))
39+
.with_body_string(format!("Hello, {name}!")))
4140
}).await;
4241

4342
// Define data structures for JSON
@@ -64,7 +63,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
6463

6564
HttpResponse::new(StatusCode::Ok)
6665
.with_json(&data)
67-
.map_err(|e| ServerError::InternalError(format!("JSON error: {}", e)))
66+
.map_err(|e| ServerError::InternalError(format!("JSON error: {e}")))
6867
},
6968
Method::POST => {
7069
// Process the request and return a response
@@ -74,7 +73,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
7473

7574
HttpResponse::new(StatusCode::Created)
7675
.with_json(&data)
77-
.map_err(|e| ServerError::InternalError(format!("JSON error: {}", e)))
76+
.map_err(|e| ServerError::InternalError(format!("JSON error: {e}")))
7877
},
7978
_ => Err(ServerError::InternalError("Unexpected method".to_string())),
8079
}
@@ -99,12 +98,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
9998

10099
HttpResponse::new(StatusCode::Created)
101100
.with_json(&response)
102-
.map_err(|e| ServerError::InternalError(format!("JSON error: {}", e)))
101+
.map_err(|e| ServerError::InternalError(format!("JSON error: {e}")))
103102
},
104103
Err(e) => {
105104
Ok(HttpResponse::new(StatusCode::BadRequest)
106105
.with_content_type("text/plain")
107-
.with_body_string(format!("Invalid JSON: {}", e)))
106+
.with_body_string(format!("Invalid JSON: {e}")))
108107
}
109108
}
110109
}).await;
@@ -131,7 +130,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
131130
let mut response_body = String::from("Request Headers:\n\n");
132131

133132
for (name, value) in &req.headers {
134-
response_body.push_str(&format!("{}: {}\n", name, value));
133+
response_body.push_str(&format!("{name}: {value}\n"));
135134
}
136135

137136
Ok(HttpResponse::new(StatusCode::Ok)

examples/simple_parser.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
33
use microhttp_rs::parse_request;
44
use log::{info, error};
5-
use env_logger;
65

76
fn main() {
87
// Initialize the logger
@@ -20,11 +19,11 @@ fn main() {
2019
info!("Version: {}", request.version);
2120
info!("Headers:");
2221
for (name, value) in &request.headers {
23-
info!(" {}: {}", name, value);
22+
info!(" {name}: {value}");
2423
}
2524
}
2625
Err(err) => {
27-
error!("Error parsing request: {}", err);
26+
error!("Error parsing request: {err}");
2827
}
2928
}
3029

@@ -36,7 +35,7 @@ fn main() {
3635
error!("Unexpectedly parsed invalid request!");
3736
}
3837
Err(err) => {
39-
info!("Expected error parsing invalid request: {}", err);
38+
info!("Expected error parsing invalid request: {err}");
4039
}
4140
}
4241
}

examples/simple_server.rs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};
44
use tokio::net::TcpListener;
55
use microhttp_rs::{parse_request, ParserError};
66
use log::{info, error, debug};
7-
use env_logger;
87

98
#[tokio::main]
109
async fn main() -> std::io::Result<()> {
@@ -17,7 +16,7 @@ async fn main() -> std::io::Result<()> {
1716
loop {
1817
// Accept incoming connections
1918
let (mut socket, addr) = listener.accept().await?;
20-
info!("Connection from: {}", addr);
19+
info!("Connection from: {addr}");
2120

2221
// Spawn a new task for each connection
2322
tokio::spawn(async move {
@@ -26,7 +25,7 @@ async fn main() -> std::io::Result<()> {
2625
// Read data from the socket
2726
match socket.read(&mut buf).await {
2827
Ok(n) if n > 0 => {
29-
debug!("Received {} bytes", n);
28+
debug!("Received {n} bytes");
3029

3130
// Parse the HTTP request
3231
let response = match parse_request(&buf[..n]) {
@@ -50,18 +49,18 @@ async fn main() -> std::io::Result<()> {
5049
)
5150
},
5251
Err(err) => {
53-
error!("Error parsing request: {}", err);
52+
error!("Error parsing request: {err}");
5453

5554
// Generate an error response
5655
let error_message = match err {
5756
ParserError::InvalidPath => "Invalid HTTP path".to_string(),
58-
ParserError::MissingHeader(header) => format!("Required header is missing: {}", header),
57+
ParserError::MissingHeader(header) => format!("Required header is missing: {header}"),
5958
ParserError::InvalidHeaderFormat => "Invalid header format".to_string(),
60-
ParserError::InvalidMethod(method) => format!("Invalid HTTP method: {}", method),
61-
ParserError::InvalidVersion(version) => format!("Invalid HTTP version: {}", version),
62-
ParserError::MalformedRequestLine(line) => format!("Malformed request line: {}", line),
59+
ParserError::InvalidMethod(method) => format!("Invalid HTTP method: {method}"),
60+
ParserError::InvalidVersion(version) => format!("Invalid HTTP version: {version}"),
61+
ParserError::MalformedRequestLine(line) => format!("Malformed request line: {line}"),
6362
ParserError::EmptyRequest => "Empty request".to_string(),
64-
ParserError::JsonError(e) => format!("JSON parsing error: {}", e),
63+
ParserError::JsonError(e) => format!("JSON parsing error: {e}"),
6564
};
6665

6766
format!(
@@ -78,14 +77,14 @@ async fn main() -> std::io::Result<()> {
7877

7978
// Write the response back to the client
8079
if let Err(e) = socket.write_all(response.as_bytes()).await {
81-
error!("Error writing response: {}", e);
80+
error!("Error writing response: {e}");
8281
}
8382
},
8483
Ok(_) => {
8584
info!("Client closed connection");
8685
},
8786
Err(e) => {
88-
error!("Error reading from socket: {}", e);
87+
error!("Error reading from socket: {e}");
8988
}
9089
}
9190
});

src/parser/method.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,19 @@ use crate::parser::error::Error;
88
/// HTTP request methods as defined in RFC 7231 and common extensions.
99
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1010
pub enum Method {
11+
/// GET method: Requests a representation of the specified resource.
1112
GET,
13+
/// POST method: Submits data to be processed to the identified resource.
1214
POST,
15+
/// PUT method: Replaces all current representations of the target resource with the request payload.
1316
PUT,
17+
/// DELETE method: Deletes the specified resource.
1418
DELETE,
19+
/// HEAD method: Same as GET but only transfers the status line and header section.
1520
HEAD,
21+
/// OPTIONS method: Describes the communication options for the target resource.
1622
OPTIONS,
23+
/// PATCH method: Applies partial modifications to a resource.
1724
PATCH,
1825
}
1926

src/parser/mod.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ mod request;
77
mod method;
88
mod version;
99
mod error;
10-
mod tests;
1110

1211
// Re-export public items
1312
pub use request::HttpRequest;
@@ -16,4 +15,4 @@ pub use version::HttpVersion;
1615
pub use error::Error;
1716

1817
// Re-export the parse_request function
19-
pub use request::parse_request;
18+
pub use request::parse_request;

src/parser/version.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,11 @@ use crate::parser::error::Error;
88
/// Supported HTTP protocol versions.
99
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1010
pub enum HttpVersion {
11+
/// HTTP/1.0: The first version of the HTTP protocol widely used on the web.
1112
Http10,
13+
/// HTTP/1.1: Improved version with persistent connections, chunked transfer encoding, and more.
1214
Http11,
15+
/// HTTP/2.0: Major revision with multiplexing, header compression, and server push capabilities.
1316
Http20,
1417
}
1518

@@ -34,4 +37,4 @@ impl fmt::Display for HttpVersion {
3437
HttpVersion::Http20 => write!(f, "HTTP/2"),
3538
}
3639
}
37-
}
40+
}

src/server/response.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,31 @@ use crate::server::error::Error;
88
/// HTTP status codes with their standard reason phrases.
99
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1010
pub enum StatusCode {
11+
/// 200 OK: The request has succeeded.
1112
Ok = 200,
13+
/// 201 Created: The request has been fulfilled and a new resource has been created.
1214
Created = 201,
15+
/// 202 Accepted: The request has been accepted for processing, but processing has not been completed.
1316
Accepted = 202,
17+
/// 204 No Content: The server has fulfilled the request but does not need to return a response body.
1418
NoContent = 204,
19+
/// 400 Bad Request: The server cannot process the request due to a client error.
1520
BadRequest = 400,
21+
/// 401 Unauthorized: Authentication is required and has failed or has not been provided.
1622
Unauthorized = 401,
23+
/// 403 Forbidden: The server understood the request but refuses to authorize it.
1724
Forbidden = 403,
25+
/// 404 Not Found: The requested resource could not be found.
1826
NotFound = 404,
27+
/// 405 Method Not Allowed: The request method is not supported for the requested resource.
1928
MethodNotAllowed = 405,
29+
/// 500 Internal Server Error: The server encountered an unexpected condition.
2030
InternalServerError = 500,
31+
/// 501 Not Implemented: The server does not support the functionality required to fulfill the request.
2132
NotImplemented = 501,
33+
/// 502 Bad Gateway: The server received an invalid response from an upstream server.
2234
BadGateway = 502,
35+
/// 503 Service Unavailable: The server is currently unable to handle the request.
2336
ServiceUnavailable = 503,
2437
}
2538

0 commit comments

Comments
 (0)