chat-gpt生成的rust web框架

Golang 归档:202304
普通
浏览:577
2023-04-04 14:10:24
rust web框架,使用chat-gpt生成的代码

当问chat-gpt:

写一个rust web框架,实现了正则路由的

它给出了以下的代码,是不是能运行,可以自己试一下。

把代码帖出来

main.rs

#[macro_use]
extern crate lazy_static;
extern crate regex;
use regex::Regex;
use std::collections::HashMap;
use std::convert::From;
use std::io::{Error, ErrorKind};
use std::net::{Ipv4Addr, SocketAddrV4};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

// 定义简单的Request和Response结构体
#[derive(Debug)]
struct Request {
    method: String,
    path: String,
}

impl From<&str> for Request {
    fn from(s: &str) -> Self {
        let parts: Vec<&str> = s.split_whitespace().collect();
        Request {
            method: parts[0].to_string(),
            path: parts[1].to_string(),
        }
    }
}

#[derive(Debug)]
struct Response {
    status: u16,
    headers: HashMap<String, String>,
    body: String,
}

impl Response {
    fn new() -> Self {
        Response {
            status: 200,
            headers: HashMap::new(),
            body: String::new(),
        }
    }

    fn set_status(&mut self, status: u16) {
        self.status = status;
    }

    fn set_header(&mut self, key: &str, value: &str) {
        self.headers.insert(key.to_string(), value.to_string());
    }

    fn set_body(&mut self, body: &str) {
        self.body = body.to_string();
    }

    fn to_string(&self) -> String {
        let mut s = format!("HTTP/1.1 {}\r\n", self.status);
        for (key, value) in &self.headers {
            s += &format!("{}: {}\r\n", key, value);
        }
        s += "\r\n";
        s += &self.body;
        s
    }
}

// 定义路由结构体
struct Router<'a> {
    routes: Vec<Route<'a>>,
}

impl<'a> Router<'a> {
    fn new() -> Self {
        Router { routes: vec![] }
    }

    fn add_route(&mut self, method: &str, path: &str, handler: Handler<'a>) {
        self.routes.push(Route {
            method: method.to_string(),
            path_regex: Regex::new(path).unwrap(),
            handler: handler,
        });
    }

    fn handle_request(&self, request: &Request) -> Result<Response, Error> {
        for route in &self.routes {
            if route.method == request.method {
                if let Some(captures) = route.path_regex.captures(&request.path) {
                    let mut params = HashMap::new();
                    for (i, name) in route.path_regex.capture_names().enumerate() {
                        if let Some(name) = name {
                            params.insert(name.to_string(), captures[i].to_string());
                        }
                    }
                    return (route.handler)(request, &params);
                }
            }
        }
        Err(Error::new(ErrorKind::NotFound, "Not Found"))
    }
}

type Handler<'a> = Box<dyn Fn(&Request, &HashMap<String, String>) -> Result<Response, Error> + 'a>;

struct Route<'a> {
    method: String,
    path_regex: Regex,
    handler: Handler<'a>,
}

fn main() {
    let router = Arc::new(Mutex::new(Router::new()));

    // 添加路由规则
    let mut router_lock = router.lock().unwrap();
    router_lock.add_route(
        "GET",
        r"^/$",
        Box::new(|_, _| {
            let mut response = Response::new();
            response.set_header("Content-Type", "text/plain");
            response.set_body("Hello, Rust Web Framework!");
            Ok(response)
        }),
    );
    router_lock.add_route(
        "GET",
        r"^/users/(?P<user_id>\d+)$",
        Box::new(|_, params| {
            let mut response = Response::new();
            response.set_header("Content-Type", "text/plain");
            response.set_body(&format!("User ID: {}", params.get("user_id").unwrap()));
            Ok(response)
        }),
    );
    drop(router_lock);

    let server_addr = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080);
    let listener = std::net::TcpListener::bind(server_addr).unwrap();

    for stream in listener.incoming() {
        let router = router.clone();
        thread::spawn(move || {
            let mut stream = stream.unwrap();
            let mut buf = [0; 1024];
            stream.read(&mut buf).unwrap();
            let request = Request::from(std::str::from_utf8(&buf).unwrap());
            let response = router.lock().unwrap().handle_request(&request).unwrap_or_else(|err| {
                let mut response = Response::new();
                response.set_status(404);
                response.set_body(&err.to_string());
                response
            });
            thread::sleep(Duration::from_secs(1));
            stream.write(response.to_string().as_bytes()).unwrap();
            stream.flush().unwrap();
        });
    }
}
注意事项
  • 此文章对你有帮助,对作者表示感谢(微信):
  • 本文地址:https://22v.net/article/3268/
  • 转载本文时,请注明转载自“SamBlog”的字样。
  • 如此文章有损您的合法权益,请使用页面底部的邮箱与我取得联系。
分类目录
文章归档
友情站点