A simple HTTP server written in Rust for learning and study purposes.
git clone https://github.com/kev1n999/http-server2
cd http-server2Edit src/main.rs and set the desired host and port:
const HOST: &str = "127.0.0.1:8000";The default address is 127.0.0.1:8000.
cargo build
cargo runOr simply:
cargo runNavigate to:
http://localhost:8000
Routes can be registered in server/routes/routes.rs by returning a Vec<Route>.
struct Route {
method: Method, // HTTP method (GET, POST, PUT, PATCH, DELETE)
path: String, // Route path
handler: Handler, // Function responsible for handling the request
}Create a route using:
Route::new(method, path, handler)Handler functions can be created inside server/handler/.
Example: responding to a GET / request.
pub fn home(ctx: &mut Context) -> Result<(), std::io::Error> {
let home_file = parse_static_file("home.html")?;
let response = Response::new(
StatusCode::Ok,
ContentType::Html,
&home_file,
);
ctx.send(response)
}In this example:
parse_static_file()loads the file contents.Response::new()creates an HTTP response.ctx.send()sends the response to the client.
The request body can be accessed through the request context:
pub fn response(ctx: &mut Context) -> Result<(), std::io::Error> {
let Request { body, .. } = &ctx.request;
}The body is stored as a Vec<u8>.
Example: handling a POST /sum request.
pub fn sum(ctx: &mut Context) -> Result<(), std::io::Error> {
let Request { body, .. } = &ctx.request;
#[derive(Deserialize)]
struct Sum {
x: i32,
y: i32,
}
let json: Sum = parse_json(body)?;
let sum = json.x + json.y;
let response = Response::new(
StatusCode::Ok,
ContentType::Text,
&sum.to_string(),
);
ctx.send(response)
}The routes() function returns all available routes:
pub fn routes() -> Vec<Route> {
vec![
Route::new(Method::Get, "/".to_string(), home),
]
}Static files should be placed inside server/public.
Supported file types include:
.html.css.js
struct StaticFile {
path: String,
content_type: ContentType,
}Where:
pathis the public URL path (e.g./css/style.css).content_typeis the file MIME type.
Static files are registered through the static_files() function:
pub fn static_files() -> Vec<StaticFile> {
vec![
StaticFile::new(
"/js/calc.js".to_string(),
ContentType::JavaScript,
),
StaticFile::new(
"/css/calc.css".to_string(),
ContentType::Css,
),
]
}