Skip to content

Commit

Permalink
Rust/may minihttp (#7899)
Browse files Browse the repository at this point in the history
* update v

* rust: may_minihttp

* fix: remove body from GET /

* fix: remove body from POST /user

* Update rust/may_minihttp/Cargo.toml

* Update rust/may_minihttp/config.yaml

---------

Co-authored-by: Marwan Rabbâa <waghanza@gmail.com>
  • Loading branch information
enghitalo and waghanza authored Oct 26, 2024
1 parent 9556502 commit 6a4374d
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
7 changes: 7 additions & 0 deletions rust/may_minihttp/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "server"
version = "0.0.0"
edition = "2021"

[dependencies]
may_minihttp = "0.1"
3 changes: 3 additions & 0 deletions rust/may_minihttp/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
framework:
github: Xudong-Huang/may_minihttp
version: 0.1
65 changes: 65 additions & 0 deletions rust/may_minihttp/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
use std::io;

use may_minihttp::{HttpService, HttpServiceFactory, Request, Response};

// Routes
/*
GET /
GET /user/:id
POST /user
*/

#[derive(Clone)]
struct WebFramework;

impl HttpService for WebFramework {
fn call(&mut self, req: Request, rsp: &mut Response) -> io::Result<()> {
let method = req.method();
// println!("method: {:?}", method);

let path = req.path();
// println!("path: {:?}", path);

match (method, path) {
("GET", "/") => {
rsp.header("Content-Type: text/plain");
}

(method_, path_) if path_.starts_with("/user") => {
if method_ == "GET" {
let id = path_.split("/").last().unwrap();
rsp.header("Content-Type: text/plain");

let body_response = format!("{}", id);
rsp.body_mut().extend_from_slice(body_response.as_bytes());
} else if method_ == "POST" {
rsp.status_code(200, "OK");
}
}
("POST", "/user") => {
rsp.header("Content-Type: text/plain");
}
_ => {
rsp.status_code(404, "Not Found");
}
}

Ok(())
}
}

struct HttpServer {}

impl HttpServiceFactory for HttpServer {
type Service = WebFramework;

fn new_service(&self, _: usize) -> Self::Service {
WebFramework {}
}
}

fn main() {
let http_server = HttpServer {};
let server = http_server.start("0.0.0.0:3000").unwrap();
server.join().unwrap();
}

0 comments on commit 6a4374d

Please sign in to comment.