Skip to content

Commit

Permalink
Update docs, README.md and cargo, Add doctests
Browse files Browse the repository at this point in the history
  • Loading branch information
emrecancorapci committed Jul 15, 2024
1 parent e99073a commit 65022a2
Show file tree
Hide file tree
Showing 8 changed files with 74 additions and 44 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "krustie"
version = "0.1.7"
version = "0.1.8"
description = "Krustie is a backend framework written in Rust. Currently, it is a work in progress and not yet ready for production use."
categories = ["network-programming", "web-programming::http-server"]
keywords = ["http", "web", "framework"]
Expand Down
43 changes: 4 additions & 39 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,55 +9,26 @@ Krustie is a backend framework written in Rust. It is currently a work in progre

## Features

- Basic request and response handling
- Stackable Router
- General Middleware support
- Router Middleware support
- Middleware support
- JSON parsing ([serde_json](https://crates.io/crates/serde_json))

### Builtin Middlewares

- Static file serving
- Gzip encoding ([flate2](https://crates.io/crates/flate2))

## Getting Started

### Prerequisites

Before you begin, ensure you have the following installed:

- [Rust](https://www.rust-lang.org/)
- [Cargo](https://doc.rust-lang.org/cargo/)

### Installation

#### Add Krustie to your project

Include it in your `Cargo.toml`:

```toml
[dependencies]
krustie = "0.1.6"
```

Run the following Cargo command in your project directory:

```bash
cargo add krustie
```

#### Start your server
## Start your server

```rust
use krustie::{ Server, Router, StatusCodes };
use krustie::{ response::ContentType, Router, Server, StatusCode };

fn main() {
let mut server = Server::create();
let mut router = Router::new();

router.get(|_, res| {
res.status(StatusCode::Ok)
.body(b"Hello World!".to_vec(), "text/plain");
res.status(StatusCode::Ok).body(b"Hello World!".to_vec(), ContentType::Text);
});

server.use_handler(router);
Expand All @@ -66,12 +37,6 @@ fn main() {
}
```

#### Run your server

```bash
cargo run
```

## Contributing

As an inexperienced developer contributions will be welcomed. Please open an issue or a pull request.
25 changes: 25 additions & 0 deletions src/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,31 @@ pub use serde_json::Result as JsonResult;
pub use serde_json::to_string as struct_to_string;

/// Converts a `JsonValue` (`serde_json::Value`) to a string
///
/// # Example
///
/// ```rust
/// fn post_req(req: &Request, res: &mut Response) {
/// match req.get_body() {
/// RequestBody::Json(body) => {
/// let server_key_option = body.get("server");
///
/// match get_string_from_json(server_key_option).unwrap() {
/// "Krustie" => {
/// res.status(StatusCode::Ok).body_json(body.clone());
/// },
/// _ => {
/// res.status(StatusCode::try_from(201).unwrap()).body_json(
/// json!({"error": "Invalid server"})
/// );
/// }
/// }
/// },
/// _ => {
/// res.status(StatusCode::BadRequest).body_json(json!({"error": "Invalid JSON"}));
/// }
/// }
/// }
pub fn get_string_from_json(json_key: Option<&JsonValue>) -> Option<String> {
json_key.map(|value| trim_json_string(value.to_string()))
}
Expand Down
36 changes: 35 additions & 1 deletion src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ impl Request {
/// fn get(request: &Request, response: &mut Response) {
/// let content_type = request.get_header("content-type");
/// }
/// ```
pub fn get_header(&self, key: &str) -> Option<&String> {
self.headers.get(key)
}
Expand All @@ -82,25 +83,58 @@ impl Request {
/// }
/// }
/// }
///
/// ```
pub fn get_body(&self) -> &RequestBody {
&self.body
}

/// Adds a local variable to the http request
///
/// `Local` variables can be used to store data that can be defined in a *middleware* and accessed in the *controller*
///
/// # Example
///
/// ```rust
/// use krustie::{ Request, Response };
///
/// fn get(request: &Request, response: &mut Response) {
/// request.add_local("user_id", "123");
/// }
/// ```
pub fn add_local(&mut self, key: &str, value: &str) {
self.locals.insert(key.to_string(), value.to_string());
}

/// Returns the value of the local variable
///
/// `Local` variables can be used to store data that can be defined in a *middleware* and accessed in the *controller*
///
/// # Example
///
/// ```rust
/// use krustie::{ Request, Response };
///
/// fn get(request: &Request, response: &mut Response) {
/// let user_id = request.get_local("user_id");
/// }
/// ```
pub fn get_local(&self, key: &str) -> Option<&String> {
self.locals.get(key)
}

/// Returns the peer address of the HTTP request
///
/// The peer address is the address of the client that made the request
///
/// # Example
///
/// ```rust
/// use krustie::{ Request, Response };
///
/// fn get(request: &Request, response: &mut Response) {
/// let peer_addr: &SocketAddr = request.get_peer_addr();
/// }
/// ```
pub fn get_peer_addr(&self) -> &SocketAddr {
&self.peer_addr
}
Expand Down
1 change: 1 addition & 0 deletions src/response/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ impl Response {
/// fn get(request: &Request, response: &mut Response) {
/// response.body_json(json!({"message": "Hello, World!"}));
/// }
/// ```
pub fn body_json(&mut self, data: JsonValue) -> &mut Self {
let json = serde_json::to_string(&data).unwrap();
self.body(json.as_bytes().to_vec(), ContentType::Json);
Expand Down
2 changes: 1 addition & 1 deletion src/response/content_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub enum ContentType {
/// Represents the `application/zip` content type
Zip,
// Image
/// Represents the `image/png` content type
/// Represents the `image/png` content type
Png,
/// Represents the `image/jpeg` content type
Jpeg,
Expand Down
7 changes: 6 additions & 1 deletion src/response/utilities.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
//! Response utilities
//!
//!
//! This module contains utility functions for the response object.
use std::collections::HashMap;
Expand Down Expand Up @@ -37,6 +37,7 @@ impl Response {
/// println!("{}: {}", key, value);
/// }
/// }
/// ```
pub fn get_headers(&self) -> &HashMap<String, String> {
&self.headers
}
Expand All @@ -56,6 +57,7 @@ impl Response {
/// None => println!("Server header not found")
/// }
/// }
/// ```
pub fn get_header(&self, key: &str) -> Option<&String> {
self.headers.get(key)
}
Expand All @@ -70,6 +72,7 @@ impl Response {
/// fn get(request: &Request, response: &mut Response) {
/// let body = response.get_body();
/// }
/// ```
pub fn get_body(&mut self) -> &Vec<u8> {
&mut self.body
}
Expand All @@ -84,6 +87,7 @@ impl Response {
/// fn get(request: &Request, response: &mut Response) {
/// let body = response.get_body();
/// }
/// ```
pub fn get_body_mut(&mut self) -> &mut Vec<u8> {
&mut self.body
}
Expand All @@ -106,6 +110,7 @@ impl Response {
///
/// response.update_body(b"Goodbye, Mars!".to_vec());
/// }
/// ```
pub fn update_body(&mut self, body: Vec<u8>) -> Result<(), String> {
if self.body.len() == 0 {
return Err("Request has no body.".to_string());
Expand Down

0 comments on commit 65022a2

Please sign in to comment.