Skip to content

Commit

Permalink
Merge pull request #7 from Basicprogrammer10/0.2.1
Browse files Browse the repository at this point in the history
✨ Release 0.2.1
  • Loading branch information
connorslade authored Dec 4, 2021
2 parents dd318f9 + 1c84d32 commit 6b47364
Show file tree
Hide file tree
Showing 29 changed files with 888 additions and 447 deletions.
33 changes: 0 additions & 33 deletions .vscode/launch.json

This file was deleted.

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.

5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "afire"
version = "0.2.0"
version = "0.2.1"
authors = ["Connor Slade <connor@connorcode.com>"]
edition = "2018"

Expand All @@ -22,6 +22,7 @@ default = ["panic_handler", "thread_pool", "cookies", "dynamic_resize"]
# Extions
rate_limit = []
logging = []
serve_static = []

# Default On
panic_handler = []
Expand All @@ -31,4 +32,4 @@ dynamic_resize = []

[dev-dependencies]
# Enable rate_limit and logging features for examples
afire = { path = ".", features = ["rate_limit", "logging"] }
afire = { path = ".", features = ["rate_limit", "logging", "serve_static"] }
27 changes: 23 additions & 4 deletions Changelog.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,26 @@
# 0.2.1
- Only Build common::remove_address_port if logger or rate-limiter are enabled
- Make Header name / value Public
- Serve Static Middleware
- Make Routes use Closures
- Remove Threadpool (for now)
- Make Error handler use a closure
- Rename `set_error_handler` to `error_handler`
- Rename `set_socket_timeout` to `socket_timeout`
- Update Serve Static Example to use Middleware
- Allow for Manually setting the reason phrase
- Support URL encoded cookies
- Rename `add_default_header` to `default_header`
- Store Raw Request data and Request body as `Vec<u8>`
- Fix Panic Handler feature compile problems
- Dont use an Option for Vec of default headers
- Fix Header Parseing
- Add a `header` method on Request to get headers

# 0.2.0
- Response Overhaul, Now more like a Response Builder
- Update *every* example with new syntax...
- Small improvement to Query parseing
- Small improvement to Query parsing
- Update SetCookie Function Names
- Update Cookie Example
- Add a Build Script to write the Readme from the docstring in lib.rs
Expand All @@ -14,12 +33,12 @@

# 0.1.7
- Add Panic Message to Error Handel
- Add http.rs to move raw http parseing out of server.rs
- Add http.rs to move raw http parsing out of server.rs
- Start / Start Threaded returns Option
- Add .unwrap to all server.starts in examples
- Add http.rs to move raw http parsing out of server.rs
- Dont give up on cookie parsing if cookie header is malformed
- Add optinal Socket Timeout
- Add optional Socket Timeout
- Add Socket Timeout Docs

# 0.1.6
Expand All @@ -31,7 +50,7 @@
- Ignore extra slashes in path
- Remove nose.txt... don't know how that got there :P
- Don't unwrap stream.read, ignore errors like a good programmer
- Fix Routeing Issue
- Fix Routing Issue
- Ignore Case in Method String
- Add different Reason Phrase for the status codes
- Update Server Header to add Version
Expand Down
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# 🔥 afire <a href="https://github.com/Basicprogrammer10/afire/actions"><img src="https://img.shields.io/github/workflow/status/Basicprogrammer10/afire/CI?label=Tests"></a> <a href="https://www.codefactor.io/repository/github/basicprogrammer10/watertemp"><a href="#"><img src="https://img.shields.io/tokei/lines/github/Basicprogrammer10/afire?label=Total%20Lines"></a> <a href="https://crates.io/crates/afire"><img src="https://img.shields.io/crates/d/afire?label=Downloads"></a>
# 🔥 afire <a href="https://github.com/Basicprogrammer10/afire/actions"><img src="https://img.shields.io/github/workflow/status/Basicprogrammer10/afire/CI?label=Tests"></a> <a href="#"><img src="https://img.shields.io/tokei/lines/github/Basicprogrammer10/afire?label=Total%20Lines"></a> <a href="https://crates.io/crates/afire"><img src="https://img.shields.io/crates/d/afire?label=Downloads"></a>

A blazing fast dependency free web framework for Rust

Expand All @@ -8,12 +8,12 @@ Just add the following to your `Cargo.toml`:

```toml
[dependencies]
afire = "0.2.0"
afire = "0.2.1"
```

## 📄 Info

This is kinda like express.js for rust. It is not _that_ complicated but it still makes development of apis / servers much easier. It supports Middleware and comes with some built in for Logging and Rate limiting.
This is kinda like express.js for rust. It is not _that_ complicated but it still makes development of apis / web servers much easier. It supports Middleware and comes with some built in for Static File Serving, Logging and Rate limiting.

For more information on this lib check the docs [here](https://crates.io/crates/afire)

Expand Down Expand Up @@ -44,7 +44,7 @@ server.route(Method::GET, "/", |_req| {
server.start().unwrap();

// Or use multi threading *experimental*
server.start_threaded(8);
// server.start_threaded(8);
```

## 🔧 Features
Expand All @@ -59,7 +59,7 @@ For these you will need to enable the feature.
To use these extra features enable them like this:

```toml
afire = { version = "0.2.0", features = ["rate_limit", "logging"] }
afire = { version = "0.2.1", features = ["rate_limit", "logging", "serve_static"] }
```

- Threading
Expand All @@ -71,5 +71,5 @@ use afire::{Server, Method, Response, Header};

let mut server: Server = Server::new("localhost", 8080);

server.start_threaded(8);
// server.start_threaded(8);
```
5 changes: 5 additions & 0 deletions examples/01_basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ fn main() {
// Define a handler for GET "/"
server.route(Method::GET, "/", |_req| {
Response::new()
// By default the status is 200
.status(200)
// By default the reason phrase is derived from the status
.reason("OK!")
// Although is is named `text` it takes any type that impls Display
// So for example numbers work too
.text("Hi :P")
.header(Header::new("Content-Type", "text/plain"))
});
Expand Down
2 changes: 1 addition & 1 deletion examples/04_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ fn main() {
// Instead it is part of the req.body but as a string
// We will need to parse it get it as a query
// This is *super* easy to do with afire
let body_data = Query::from_body(req.body).unwrap();
let body_data = Query::from_body(String::from_utf8(req.body).unwrap()).unwrap();

let name = body_data
.get("name")
Expand Down
2 changes: 1 addition & 1 deletion examples/05_header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ fn main() {
// If the same header is defined in the route it will be put before the default header
// Although it is not garunteed to be the one picked by the client it usually is
// At the bottom of this file is a representation of the order of the headers
server.add_default_header(Header::new(
server.default_header(Header::new(
"X-Server-Header",
"This is a server wide header",
));
Expand Down
2 changes: 1 addition & 1 deletion examples/06_error_handling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ fn main() {
// You can optionally define a custom error handler
// This can be defined anywhere in the server and will take affect for all routes
// Its like a normal route, but it will only be called if the route panics
server.set_error_handler(|_req, err| {
server.error_handler(|_req, err| {
Response::new()
.status(500)
.text(format!(
Expand Down
91 changes: 28 additions & 63 deletions examples/07_serve_static.rs
Original file line number Diff line number Diff line change
@@ -1,54 +1,40 @@
use afire::{Header, Response, Server};
use std::fs;
use afire::{Header, Response, ServeStatic, Server};

// Serve static files from a directory
// Afire middleware makes this *easy*

const STATIC_DIR: &str = "examples/data";

fn main() {
// Create a new Server instance on localhost port 8080
let mut server: Server = Server::new("localhost", 8080);

// Define a method to handle all requests
// Other methods can be defined after this one and take a higher priority
server.all(|req| {
// Gen the local path to the requested file
// Im removing '/..' in the path to avoid directory traversal exploits
let mut path = format!("{}{}", STATIC_DIR, req.path.replace("/..", ""));

// Add Index.html if path ends with /
// This will cause the server to automatically serve the index.html
if path.ends_with('/') {
path.push_str("index.html");
}

// Also add '/index.html' if path dose not end with a file
// Ex 'page' will return 'page/index.html'
if !path.split('/').last().unwrap_or_default().contains('.') {
path.push_str("/index.html");
}

// Try to read File
// Using read over read_to_string is important to allow serving non utf8 files
match fs::read(&path) {
// If its found send it as response
// We are setting the Content-Type header with the file extension through a match expression
Ok(content) => Response::new()
.status(200)
.bytes(content)
.header(Header::new("Content-Type", get_type(&path))),

// If not read and send 404.html
// If that file is not found, fallback to sending "Not Found :/"
Err(_) => Response::new()
.status(404)
.bytes(
fs::read(format!("{}/404.html", STATIC_DIR))
.unwrap_or_else(|_| "Not Found :/".as_bytes().to_owned()),
)
.header(Header::new("Content-Type", "text/html")),
}
});
// Make a new static file server with a path
ServeStatic::new(STATIC_DIR)
// Middleware here works much diffrnetly to afire middleware
// The middleware priority is still by most recently defined
// But this middleware takes functions only - no closures
// and resultes of the middleware are put togther so more then one ac affect thre response
//
// Args:
// - req: Client Request
// - res: Current Server Response
// - suc: File to serve was found
.middleware(|req, res, suc| {
// Print path sevred
println!("Staticly Served: {}", req.path);

// Return none to not mess with response
Some((res.header(Header::new("X-Static-Serve", "true")), suc))
})
// Function that runs when no file is found to serve
// This will run before middleware
.not_found(|_req, _dis| Response::new().status(404).text("Page Not Found!"))
// Add an extra mime type to the server
// It has alot already
.mime_type("key", "value")
// Attatch the middleware to the server
.attach(&mut server);

println!(
"[07] Listening on http://{}:{}",
Expand All @@ -60,24 +46,3 @@ fn main() {
// This will block the current thread
server.start().unwrap();
}

// Get the type MMIE content type of a file from its extension
// Thare are lots of other MMIME types but these are the most common
fn get_type(path: &str) -> &str {
match path.split('.').last() {
Some(ext) => match ext {
"html" => "text/html",
"css" => "text/css",
"js" => "application/javascript",
"png" => "image/png",
"jpg" => "image/jpeg",
"jpeg" => "image/jpeg",
"gif" => "image/gif",
"ico" => "image/x-icon",
"svg" => "image/svg+xml",
_ => "application/octet-stream",
},

None => "application/octet-stream",
}
}
2 changes: 1 addition & 1 deletion examples/10_threading.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,5 @@ fn main() {

// Start the server with 8 threads
// This will block the current thread
server.start_threaded(8);
// server.start_threaded(8);
}
2 changes: 2 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ Learn about afire's automatic route error handling and add your own error handle

Serve all static files from a directory.

Makes use of one of afire's built in extensions

## 08 - Middleware

Learn about Middleware and how to use it to log requests.
Expand Down
16 changes: 16 additions & 0 deletions examples/test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use afire::*;

fn main() {
let mut server: Server = Server::new("localhost", 8081);

server.route(Method::GET, "/", |req| {
println!("{:?}", String::from_utf8_lossy(&req.raw_data.clone()));

Response::new()
.status(200)
.text(req.body_string().unwrap())
.header(Header::new("Content-Type", "text/plain"))
});

server.start().unwrap();
}
1 change: 1 addition & 0 deletions lib/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ pub(crate) fn reason_phrase(status: u16) -> String {
/// Remove the port from an address
///
/// '192.168.1.26:1234' -> '192.168.1.26'
#[cfg(any(feature = "rate_limit", feature = "logging"))]
pub(crate) fn remove_address_port<T>(address: T) -> String
where
T: fmt::Display,
Expand Down
8 changes: 7 additions & 1 deletion lib/cookie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ It can be disabled with the `cookies` feature.

use std::fmt;

use crate::common::decode_url;

/// Represents a Cookie
#[derive(Hash, PartialEq, Eq)]
pub struct Cookie {
/// Cookie Key
pub name: String,
Expand Down Expand Up @@ -78,7 +81,10 @@ impl Cookie {
}
.trim_end_matches(';');

final_cookies.push(Cookie::new(name, value));
final_cookies.push(Cookie::new(
decode_url(name.to_owned()),
decode_url(value.to_owned()),
));
}
return Some(final_cookies);
}
Expand Down
4 changes: 3 additions & 1 deletion lib/extensions/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,9 @@ impl Logger {
new_path,
query,
headers,
req.body.replace('\n', "\\n")
String::from_utf8(req.body.clone())
.unwrap_or_default()
.replace('\n', "\\n")
))
}

Expand Down
3 changes: 3 additions & 0 deletions lib/extensions/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ pub mod ratelimit;

#[cfg(feature = "logging")]
pub mod logger;

#[cfg(feature = "serve_static")]
pub mod serve_static;
2 changes: 1 addition & 1 deletion lib/extensions/ratelimit.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::cell::RefCell;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use std::time::SystemTime;
Expand Down
Loading

0 comments on commit 6b47364

Please sign in to comment.