主頁 > 後端開發 > Rust Web 全堆疊開發之自建TCP、HTTP Server

Rust Web 全堆疊開發之自建TCP、HTTP Server

2023-05-29 07:43:58 後端開發

Rust Web 全堆疊開發之自建TCP、HTTP Server

課程簡介

預備知識

  • Rust 編程語言入門

  • https://www.bilibili.com/video/BV1hp4y1k7SV

課程主要內容

  • WebService
  • 服務器端Web App
  • 客戶端Web App(WebAssembly)
  • Web框架:Actix
  • 資料庫:PostgreSQL
  • 資料庫連接:SQLx

全部使用純Rust撰寫!

一、構建TCP Server

本節內容

  • 撰寫TCP Server和Client

std::net模塊

  • 標準庫的std::net模塊,提供網路基本功能
  • 支持TCP和UDP通信
  • TcpListener和TcpStream

創建專案

~/rust via ?? base
? cargo new s1 && cd s1
     Created binary (application) `s1` package

s1 on  master [?] via ?? 1.67.1 via ?? base
? cargo new tcpserver
     Created binary (application) `tcpserver` package

s1 on  master [?] via ?? 1.67.1 via ?? base
? cargo new tcpclient
     Created binary (application) `tcpclient` package

s1 on  master [?] via ?? 1.67.1 via ?? base
? c

s1 on  master [?] via ?? 1.67.1 via ?? base
?

目錄

s1 on  master [?] via ?? 1.67.1 via ?? base 
? tree
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
├── target
│   ├── CACHEDIR.TAG
│   └── debug
│       ├── build
│       ├── deps
│       ├── examples
│       └── incremental
├── tcpclient
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── tcpserver
    ├── Cargo.toml
    └── src
        └── main.rs

24 directories, 44 files

s1 on  master [?] via ?? 1.67.1 via ?? base 

s1/Cargo.toml

[workspace]

members = ["tcpserver", "tcpclient"]

tcpserver/src/main.rs

use std::net::TcpListener;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:3000").unwrap();
    println!("Running on port 3000...");

    // let result = listener.accept().unwrap(); // 只接收一次請求

    for stream in listener.incoming() {
        let _stream = stream.unwrap();
        println!("Connection established!")
    }
}

運行

s1 on  master [?] via ?? 1.67.1 via ?? base 
? cargo run -p tcpserver            
   Compiling tcpserver v0.1.0 (/Users/qiaopengjun/rust/s1/tcpserver)
    Finished dev [unoptimized + debuginfo] target(s) in 0.52s
     Running `target/debug/tcpserver`
Running on port 3000...

tcpclient/src/main.rs

use std::net::TcpStream;

fn main() {
    let _stream = TcpStream::connect("localhost:3000").unwrap();
}

運行

s1 on  master [?] via ?? 1.67.1 via ?? base 
? cargo run -p tcpclient
   Compiling tcpclient v0.1.0 (/Users/qiaopengjun/rust/s1/tcpclient)
    Finished dev [unoptimized + debuginfo] target(s) in 0.32s
     Running `target/debug/tcpclient`

s1 on  master [?] via ?? 1.67.1 via ?? base 
? 

s1 on  master [?] via ?? 1.67.1 via ?? base 
? cargo run -p tcpserver            
   Compiling tcpserver v0.1.0 (/Users/qiaopengjun/rust/s1/tcpserver)
    Finished dev [unoptimized + debuginfo] target(s) in 0.52s
     Running `target/debug/tcpserver`
Running on port 3000...
Connection established!

tcpserver/src/main.rs

use std::io::{Read, Write};
use std::net::TcpListener;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:3000").unwrap();
    println!("Running on port 3000...");

    // let result = listener.accept().unwrap(); // 只接收一次請求

    for stream in listener.incoming() {
        let mut stream = stream.unwrap();
        println!("Connection established!");
        let mut buffer = [0; 1024];

        stream.read(&mut buffer).unwrap();
        stream.write(&mut buffer).unwrap();
    }
}

tcpclient/src/main.rs

use std::io::{Read, Write};
use std::net::TcpStream;
use std::str;

fn main() {
    let mut stream = TcpStream::connect("localhost:3000").unwrap();
    stream.write("Hello".as_bytes()).unwrap();

    let mut buffer = [0; 5];
    stream.read(&mut buffer).unwrap();

    println!(
        "Response from server: {:?}",
        str::from_utf8(&buffer).unwrap()
    );
}

運行

s1 on  master [?] via ?? 1.67.1 via ?? base 
? cargo run -p tcpclient
   Compiling tcpclient v0.1.0 (/Users/qiaopengjun/rust/s1/tcpclient)
    Finished dev [unoptimized + debuginfo] target(s) in 0.15s
     Running `target/debug/tcpclient`
Response from server: "Hello"

s1 on  master [?] via ?? 1.67.1 via ?? base 
? 

二、構建HTTP Server - 決議 HTTP 請求

本節內容

  • 撰寫HTTP Server
  • 測驗HTTP Server

Web Server的訊息流動圖

客戶端 Internet 請求(1) -> Server (HTTP Library)->(2) Router ->(3) -> Handlers ->處理請求并回傳回應(4) 客戶端

注意

  • Rust沒有內置的HTTP支持

Web Server

  • Server
    • 監聽進來的TCP位元組流
  • Router
    • 接受HTTP請求,并決定呼叫哪個Handler
  • Handler
    • 處理HTTP請求,構建HTTP回應
  • HTTP Library
    • 解釋位元組流,把它轉化為HTTP請求
    • 把HTTP回應轉化回位元組流

構建步驟

  • 決議HTTP請求訊息
  • 構建HTTP回應訊息
  • 路由與Handler
  • 測驗Web Server

決議HTTP請求(訊息)

三個資料結構

資料結構名稱 資料型別 描述
HttpRequest struct 表示HTTP請求
Method enum 指定所允許的HTTP方法
Version enum 指定所允許的HTTP版本

HTTP請求

Structure of an HTTP Request

Request Line Method Path Version

Header Line 1

Header Line 2

Header Line 3

Empty line

Message body (optional)

s1 on  master [?] via ?? 1.67.1 via ?? base
? cargo new httpserver
warning: compiling this new package may not work due to invalid workspace configuration

current package believes it's in a workspace when it's not:
current:   /Users/qiaopengjun/rust/s1/httpserver/Cargo.toml
workspace: /Users/qiaopengjun/rust/s1/Cargo.toml

this may be fixable by adding `httpserver` to the `workspace.members` array of the manifest located at: /Users/qiaopengjun/rust/s1/Cargo.toml
Alternatively, to keep it out of the workspace, add the package to the `workspace.exclude` array, or add an empty `[workspace]` table to the package's manifest.
     Created binary (application) `httpserver` package

s1 on  master [?] via ?? 1.67.1 via ?? base
? cargo new --lib http
warning: compiling this new package may not work due to invalid workspace configuration

current package believes it's in a workspace when it's not:
current:   /Users/qiaopengjun/rust/s1/http/Cargo.toml
workspace: /Users/qiaopengjun/rust/s1/Cargo.toml

this may be fixable by adding `http` to the `workspace.members` array of the manifest located at: /Users/qiaopengjun/rust/s1/Cargo.toml
Alternatively, to keep it out of the workspace, add the package to the `workspace.exclude` array, or add an empty `[workspace]` table to the package's manifest.
     Created library `http` package

s1 on  master [?] via ?? 1.67.1 via ?? base
?

需要實作的Trait

Trait 描述
From<&str> 用于把傳進來的字串切片轉化為HttpRequest
Debug 列印除錯資訊
PartialEq 用于決議和自動化測驗腳本里做比較

目錄

s1 on  master [?] via ?? 1.67.1 via ?? base 
? tree
.
├── Cargo.lock
├── Cargo.toml
├── http
│   ├── Cargo.toml
│   └── src
│       ├── httprequest.rs
│       ├── httpresponse.rs
│       └── lib.rs
├── httpserver
│   ├── Cargo.toml
│   └── src
│       └── main.rs
├── src
│   └── main.rs
├── target
│   ├── CACHEDIR.TAG
│   └── debug
│       ├── build
│       ├── deps
│       ├── examples
│       ├── httpserver
│       ├── httpserver.d
│       ├── incremental
│       ├── libhttp.d
│       ├── libhttp.rlib
│       ├── tcpclient
│       ├── tcpclient.d
│       ├── tcpserver
│       └── tcpserver.d
├── tcpclient
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── tcpserver
    ├── Cargo.toml
    └── src
        └── main.rs

48 directories, 302 files

s1 on  master [?] via ?? 1.67.1 via ?? base 
? 

http/lib.rs

pub mod httprequest;

Cargo.toml

[workspace]

members = ["tcpserver", "tcpclient", "http", "httpserver"]

http/src/httprequest.rs

#[derive(Debug, PartialEq)]
pub enum Method {
    Get,
    Post,
    Uninitialized,
}

impl From<&str> for Method {
    fn from(s: &str) -> Method {
        match s {
            "GET" => Method::Get,
            "POST" => Method::Post,
            _ => Method::Uninitialized,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_method_into() {
        let m: Method = "GET".into();
        assert_eq!(m, Method::Get);
    }
}

運行

s1 on  master [?] via ?? 1.67.1 via ?? base 
? cargo test -p http   
   Compiling http v0.1.0 (/Users/qiaopengjun/rust/s1/http)
    Finished test [unoptimized + debuginfo] target(s) in 0.19s
     Running unittests src/lib.rs (target/debug/deps/http-ca93876a5b13f05e)

running 1 test
test httprequest::tests::test_method_into ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests http

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


s1 on  master [?] via ?? 1.67.1 via ?? base 
? 

http/src/httprequest.rs

#[derive(Debug, PartialEq)]
pub enum Method {
    Get,
    Post,
    Uninitialized,
}

impl From<&str> for Method {
    fn from(s: &str) -> Method {
        match s {
            "GET" => Method::Get,
            "POST" => Method::Post,
            _ => Method::Uninitialized,
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum Version {
    V1_1,
    V2_0,
    Uninitialized,
}

impl From<&str> for Version {
    fn from(s: &str) -> Version {
        match s {
            "HTTP/1.1" => Version::V1_1,
            _ => Version::Uninitialized,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_method_into() {
        let m: Method = "GET".into();
        assert_eq!(m, Method::Get);
    }

    #[test]
    fn test_version_into() {
        let v: Version = "HTTP/1.1".into();
        assert_eq!(v, Version::V1_1);
    }
}

運行

s1 on  master [?] via ?? 1.67.1 via ?? base 
? cargo test -p http
   Compiling http v0.1.0 (/Users/qiaopengjun/rust/s1/http)
    Finished test [unoptimized + debuginfo] target(s) in 0.58s
     Running unittests src/lib.rs (target/debug/deps/http-ca93876a5b13f05e)

running 2 tests
test httprequest::tests::test_version_into ... ok
test httprequest::tests::test_method_into ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests http

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


s1 on  master [?] via ?? 1.67.1 via ?? base 
? 

http/src/httprequest.rs

use std::collections::HashMap;

#[derive(Debug, PartialEq)]
pub enum Method {
    Get,
    Post,
    Uninitialized,
}

impl From<&str> for Method {
    fn from(s: &str) -> Method {
        match s {
            "GET" => Method::Get,
            "POST" => Method::Post,
            _ => Method::Uninitialized,
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum Version {
    V1_1,
    V2_0,
    Uninitialized,
}

impl From<&str> for Version {
    fn from(s: &str) -> Version {
        match s {
            "HTTP/1.1" => Version::V1_1,
            _ => Version::Uninitialized,
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum Resource {
    Path(String),
}

#[derive(Debug)]
pub struct HttpRequest {
    pub method: Method,
    pub version: Version,
    pub resource: Resource,
    pub headers: HashMap<String, String>,
    pub msg_body: String,
}

impl From<String> for HttpRequest {
    fn from(req: String) -> Self {
        let mut parsed_method = Method::Uninitialized;
        let mut parsed_version = Version::V1_1;
        let mut parsed_resource = Resource::Path("".to_string());
        let mut parsed_headers = HashMap::new();
        let mut parsed_msg_body = "";

        for line in req.lines() {
            if line.contains("HTTP") {
                let (method, resource, version) = process_req_line(line);
                parsed_method = method;
                parsed_resource = resource;
                parsed_version = version;
            } else if line.contains(":") {
                let (key, value) = process_header_line(line);
                parsed_headers.insert(key, value);
            } else if line.len() == 0 {
            } else {
                parsed_msg_body = line;
            }
        }

        HttpRequest {
            method: parsed_method,
            version: parsed_version,
            resource: parsed_resource,
            headers: parsed_headers,
            msg_body: parsed_msg_body.to_string(),
        }
    }
}

fn process_req_line(s: &str) -> (Method, Resource, Version) {
    let mut words = s.split_whitespace();
    let method = words.next().unwrap();
    let resource = words.next().unwrap();
    let version = words.next().unwrap();

    (
        method.into(),
        Resource::Path(resource.to_string()),
        version.into(),
    )
}

fn process_header_line(s: &str) -> (String, String) {
    let mut header_items = s.split(":");
    let mut key = String::from("");
    let mut value = https://www.cnblogs.com/QiaoPengjun/archive/2023/05/28/String::from("");
    if let Some(k) = header_items.next() {
        key = k.to_string();
    }
    if let Some(v) = header_items.next() {
        value = https://www.cnblogs.com/QiaoPengjun/archive/2023/05/28/v.to_string();
    }

    (key, value)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_method_into() {
        let m: Method ="GET".into();
        assert_eq!(m, Method::Get);
    }

    #[test]
    fn test_version_into() {
        let v: Version = "HTTP/1.1".into();
        assert_eq!(v, Version::V1_1);
    }

    #[test]
    fn test_read_http() {
        let s: String = String::from("GET /greeting HTTP/1.1\r\nHost: localhost:3000\r\nUser-Agent: curl/7.71.1\r\nAccept: */*\r\n\r\n");
        let mut headers_expected = HashMap::new();
        headers_expected.insert("Host".into(), " localhost".into());
        headers_expected.insert("Accept".into(), " */*".into());
        headers_expected.insert("User-Agent".into(), " curl/7.71.1".into());
        let req: HttpRequest = s.into();

        assert_eq!(Method::Get, req.method);
        assert_eq!(Version::V1_1, req.version);
        assert_eq!(Resource::Path("/greeting".to_string()), req.resource);
        assert_eq!(headers_expected, req.headers);
    }
}

測驗

s1 on  master [?] via ?? 1.67.1 via ?? base 
? cargo test -p http
   Compiling http v0.1.0 (/Users/qiaopengjun/rust/s1/http)
    Finished test [unoptimized + debuginfo] target(s) in 0.37s
     Running unittests src/lib.rs (target/debug/deps/http-ca93876a5b13f05e)

running 3 tests
test httprequest::tests::test_method_into ... ok
test httprequest::tests::test_version_into ... ok
test httprequest::tests::test_read_http ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests http

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


s1 on  master [?] via ?? 1.67.1 via ?? base 
? 

三、構建HTTP回應

HTTP回應

Structure of an HTTP Response

Status Line Version Status code Status text

Header Line 1

Header Line 2

Empty line

Message body(optional)

HttpResponse 需要實作的方法

需要實作的方法或trait 用途
Default trait 指定成員的默認值
new() 使用默認值創建一個新的結構體
send_response() 構建回應,將原始位元組通過TCP傳送
getter 方法 獲得成員的值
From trait 能夠將HttpResponse轉化為String

http/lib.rs

pub mod httprequest;
pub mod httpresponse;

http/src/httpresponse.rs

use std::collections::HashMap;
use std::io::{Result, Write};

#[derive(Debug, PartialEq, Clone)]
pub struct HttpResponse<'a> {
    version: &'a str,
    status_code: &'a str,
    status_text: &'a str,
    headers: Option<HashMap<&'a str, &'a str>>,
    body: Option<String>,
}

impl<'a> Default for HttpResponse<'a> {
    fn default() -> Self {
        Self {
            version: "HTTP/1.1".into(),
            status_code: "200".into(),
            status_text: "OK".into(),
            headers: None,
            body: None,
        }
    }
}

impl<'a> From<HttpResponse<'a>> for String {
    fn from(res: HttpResponse<'a>) -> String {
        let res1 = res.clone();
        format!(
            "{} {} {}\r\n{}Content-Length: {}\r\n\r\n{}",
            &res1.version(),
            &res1.status_code(),
            &res1.status_text(),
            &res1.headers(),
            &res.body.unwrap().len(),
            &res1.body()
        )
    }
}

impl<'a> HttpResponse<'a> {
    pub fn new(
        status_code: &'a str,
        headers: Option<HashMap<&'a str, &'a str>>,
        body: Option<String>,
    ) -> HttpResponse<'a> {
        let mut response: HttpResponse<'a> = HttpResponse::default();
        if status_code != "200" {
            response.status_code = status_code.into();
        };
        response.headers = match &headers {
            Some(_h) => headers,
            None => {
                let mut h = HashMap::new();
                h.insert("Content-Type", "text/html");
                Some(h)
            }
        };
        response.status_text = match response.status_code {
            "200" => "OK".into(),
            "400" => "Bad Request".into(),
            "404" => "Not Found".into(),
            "500" => "Internal Server Error".into(),
            _ => "Not Found".into(),
        };

        response.body = body;

        response
    }

    pub fn send_response(&self, write_stream: &mut impl Write) -> Result<()> {
        let res = self.clone();
        let response_string: String = String::from(res);
        let _ = write!(write_stream, "{}", response_string);

        Ok(())
    }

    fn version(&self) -> &str {
        self.version
    }

    fn status_code(&self) -> &str {
        self.status_code
    }

    fn status_text(&self) -> &str {
        self.status_text
    }

    fn headers(&self) -> String {
        let map: HashMap<&str, &str> = self.headers.clone().unwrap();
        let mut header_string: String = "".into();
        for (k, v) in map.iter() {
            header_string = format!("{}{}:{}\r\n", header_string, k, v);
        }
        header_string
    }

    pub fn body(&self) -> &str {
        match &self.body {
            Some(b) => b.as_str(),
            None => "",
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_response_struct_creation_200() {
        let response_actual = HttpResponse::new("200", None, Some("xxxx".into()));
        let response_expected = HttpResponse {
            version: "HTTP/1.1",
            status_code: "200",
            status_text: "OK",
            headers: {
                let mut h = HashMap::new();
                h.insert("Content-Type", "text/html");
                Some(h)
            },
            body: Some("xxxx".into()),
        };
        assert_eq!(response_actual, response_expected);
    }

    #[test]
    fn test_response_struct_creation_404() {
        let response_actual = HttpResponse::new("404", None, Some("xxxx".into()));
        let response_expected = HttpResponse {
            version: "HTTP/1.1",
            status_code: "404",
            status_text: "Not Found",
            headers: {
                let mut h = HashMap::new();
                h.insert("Content-Type", "text/html");
                Some(h)
            },
            body: Some("xxxx".into()),
        };
        assert_eq!(response_actual, response_expected);
    }

    #[test]
    fn test_http_response_creation() {
        let response_expected = HttpResponse {
            version: "HTTP/1.1",
            status_code: "404",
            status_text: "Not Found",
            headers: {
                let mut h = HashMap::new();
                h.insert("Content-Type", "text/html");
                Some(h)
            },
            body: Some("xxxx".into()),
        };
        let http_string: String = response_expected.into();
        let actual_string =
            "HTTP/1.1 404 Not Found\r\nContent-Type:text/html\r\nContent-Length: 4\r\n\r\nxxxx";
        assert_eq!(http_string, actual_string);
    }
}

測驗

s1 on  master [?] via ?? 1.67.1 via ?? base 
? cargo test -p http
   Compiling http v0.1.0 (/Users/qiaopengjun/rust/s1/http)
    Finished test [unoptimized + debuginfo] target(s) in 0.70s
     Running unittests src/lib.rs (target/debug/deps/http-ca93876a5b13f05e)

running 6 tests
test httprequest::tests::test_version_into ... ok
test httprequest::tests::test_method_into ... ok
test httpresponse::tests::test_response_struct_creation_200 ... ok
test httpresponse::tests::test_response_struct_creation_404 ... ok
test httpresponse::tests::test_http_response_creation ... ok
test httprequest::tests::test_read_http ... ok

test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests http

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


s1 on  master [?] via ?? 1.67.1 via ?? base 
? 

四、構建 server 模塊

目錄

s1 on  master [?] via ?? 1.67.1 via ?? base 
? tree
.
├── Cargo.lock
├── Cargo.toml
├── http
│   ├── Cargo.toml
│   └── src
│       ├── httprequest.rs
│       ├── httpresponse.rs
│       └── lib.rs
├── httpserver
│   ├── Cargo.toml
│   └── src
│       ├── handler.rs
│       ├── main.rs
│       ├── router.rs
│       └── server.rs
├── src
│   └── main.rs
├── target
│   ├── CACHEDIR.TAG
│   └── debug
│       ├── build
│       ├── deps
│       ├── examples
│       ├── httpserver
│       ├── httpserver.d
│       ├── incremental
│       ├── libhttp.d
│       ├── libhttp.rlib
│       ├── tcpclient
│       ├── tcpclient.d
│       ├── tcpserver
│       └── tcpserver.d
├── tcpclient
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── tcpserver
    ├── Cargo.toml
    └── src
        └── main.rs

58 directories, 532 files

s1 on  master [?] via ?? 1.67.1 via ?? base 
? 

httpserver/Cargo.toml

[package]
name = "httpserver"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
http = {path = "../http"}

httpserver/main.rs

mod handler;
mod router;
mod server;

use server::Server;

fn main() {
    let server = Server::new("localhost:3000");
    server.run();
}

httpserver/server.rs

use super::router::Router;
use http::httprequest::HttpRequest;
use std::io::prelude::*;
use std::net::TcpListener;
use std::str;

pub struct Server<'a> {
    socket_addr: &'a str,
}

impl<'a> Server<'a> {
    pub fn new(socket_addr: &'a str) -> Self {
        Server { socket_addr }
    }

    pub fn run(&self) {
        let connection_listener = TcpListener::bind(self.socket_addr).unwrap();
        println!("Running on {}", self.socket_addr);

        for stream in connection_listener.incoming() {
            let mut stream = stream.unwrap();
            println!("Connection established");

            let mut read_buffer = [0; 200];
            stream.read(&mut read_buffer).unwrap();

            let req: HttpRequest = String::from_utf8(read_buffer.to_vec()).unwrap().into();
            Router::route(req, &mut stream);
        }
    }
}

五、構建 router 和 handler 模塊

目錄

s1 on  master [?] via ?? 1.67.1 via ?? base 
? tree
.
├── Cargo.lock
├── Cargo.toml
├── http
│   ├── Cargo.toml
│   └── src
│       ├── httprequest.rs
│       ├── httpresponse.rs
│       └── lib.rs
├── httpserver
│   ├── Cargo.toml
│   ├── data
│   │   └── orders.json
│   ├── public
│   │   ├── 404.html
│   │   ├── health.html
│   │   ├── index.html
│   │   └── styles.css
│   └── src
│       ├── handler.rs
│       ├── main.rs
│       ├── router.rs
│       └── server.rs
├── src
│   └── main.rs
├── target
│   ├── CACHEDIR.TAG
│   └── debug
│       ├── build
│       ├── deps
│       ├── libhttp.d
│       ├── libhttp.rlib
│       ├── tcpclient
│       ├── tcpclient.d
│       ├── tcpserver
│       └── tcpserver.d
├── tcpclient
│   ├── Cargo.toml
│   └── src
│       └── main.rs
└── tcpserver
    ├── Cargo.toml
    └── src
        └── main.rs

74 directories, 805 files

s1 on  master [?] via ?? 1.67.1 via ?? base 
? 

httpserver/Cargo.toml

[package]
name = "httpserver"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
http = {path = "../http"}
serde = {version="1.0.163", features = ["derive"]}
serde_json = "1.0.96"

httpserver/src/handler.rs

use http::{httprequest::HttpRequest, httpresponse::HttpResponse};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::env;
use std::fs;

pub trait Handler {
    fn handle(req: &HttpRequest) -> HttpResponse;
    fn load_file(file_name: &str) -> Option<String> {
        let default_path = format!("{}/public", env!("CARGO_MANIFEST_DIR"));
        let public_path = env::var("PUBLIC_PATH").unwrap_or(default_path);
        let full_path = format!("{}/{}", public_path, file_name);

        let contents = fs::read_to_string(full_path);
        contents.ok()
    }
}

pub struct StaticPageHandler;
pub struct PageNotFoundHandler;
pub struct WebServiceHandler;

#[derive(Serialize, Deserialize)]
pub struct OrderStatus {
    order_id: i32,
    order_date: String,
    order_status: String,
}

impl Handler for PageNotFoundHandler {
    fn handle(_req: &HttpRequest) -> HttpResponse {
        HttpResponse::new("404", None, Self::load_file("404.html"))
    }
}

impl Handler for StaticPageHandler {
    fn handle(req: &HttpRequest) -> HttpResponse {
        let http::httprequest::Resource::Path(s) = &req.resource;
        let route: Vec<&str> = s.split("/").collect();
        match route[1] {
            "" => HttpResponse::new("200", None, Self::load_file("index.html")),
            "health" => HttpResponse::new("200", None, Self::load_file("health.html")),
            path => match Self::load_file(path) {
                Some(contents) => {
                    let mut map: HashMap<&str, &str> = HashMap::new();
                    if path.ends_with(".css") {
                        map.insert("Content-Type", "text/css");
                    } else if path.ends_with(".js") {
                        map.insert("Content-Type", "text/javascript");
                    } else {
                        map.insert("Content-Type", "text/html");
                    }
                    HttpResponse::new("200", Some(map), Some(contents))
                }
                None => HttpResponse::new("404", None, Self::load_file("404.html")),
            },
        }
    }
}

impl WebServiceHandler {
    fn load_json() -> Vec<OrderStatus> {
        let default_path = format!("{}/data", env!("CARGO_MANIFEST_DIR"));
        let data_path = env::var("DATA_PATH").unwrap_or(default_path);
        let full_path = format!("{}/{}", data_path, "orders.json");
        let json_contents = fs::read_to_string(full_path);
        let orders: Vec<OrderStatus> =
            serde_json::from_str(json_contents.unwrap().as_str()).unwrap();
        orders
    }
}

impl Handler for WebServiceHandler {
    fn handle(req: &HttpRequest) -> HttpResponse {
        let http::httprequest::Resource::Path(s) = &req.resource;
        let route: Vec<&str> = s.split("/").collect();
        // localhost:3000/api/shipping/orders
        match route[2] {
            "shipping" if route.len() > 2 && route[3] == "orders" => {
                let body = Some(serde_json::to_string(&Self::load_json()).unwrap());
                let mut headers: HashMap<&str, &str> = HashMap::new();
                headers.insert("Content-Type", "application/json");
                HttpResponse::new("200", Some(headers), body)
            }
            _ => HttpResponse::new("404", None, Self::load_file("404.html")),
        }
    }
}

httpserver/src/server.rs

use super::router::Router;
use http::httprequest::HttpRequest;
use std::io::prelude::*;
use std::net::TcpListener;
use std::str;

pub struct Server<'a> {
    socket_addr: &'a str,
}

impl<'a> Server<'a> {
    pub fn new(socket_addr: &'a str) -> Self {
        Server { socket_addr }
    }

    pub fn run(&self) {
        let connection_listener = TcpListener::bind(self.socket_addr).unwrap();
        println!("Running on {}", self.socket_addr);

        for stream in connection_listener.incoming() {
            let mut stream = stream.unwrap();
            println!("Connection established");

            let mut read_buffer = [0; 200];
            stream.read(&mut read_buffer).unwrap();

            let req: HttpRequest = String::from_utf8(read_buffer.to_vec()).unwrap().into();
            Router::route(req, &mut stream);
        }
    }
}

httpserver/src/router.rs

use super::handler::{Handler, PageNotFoundHandler, StaticPageHandler, WebServiceHandler};
use http::{httprequest, httprequest::HttpRequest, httpresponse::HttpResponse};
use std::io::prelude::*;

pub struct Router;

impl Router {
    pub fn route(req: HttpRequest, stream: &mut impl Write) -> () {
        match req.method {
            httprequest::Method::Get => match &req.resource {
                httprequest::Resource::Path(s) => {
                    let route: Vec<&str> = s.split("/").collect();
                    match route[1] {
                        "api" => {
                            let resp: HttpResponse = WebServiceHandler::handle(&req);
                            let _ = resp.send_response(stream);
                        }
                        _ => {
                            let resp: HttpResponse = StaticPageHandler::handle(&req);
                            let _ = resp.send_response(stream);
                        }
                    }
                }
            },
            _ => {
                let resp: HttpResponse = PageNotFoundHandler::handle(&req);
                let _ = resp.send_response(stream);
            }
        }
    }
}

httpserver/data/orders.json

[
    {
        "order_id": 1,
        "order_date": "21 Jan 2023",
        "order_status": "Delivered"
    },
    {
        "order_id": 2,
        "order_date": "2 Feb 2023",
        "order_status": "Pending"
    }
]

httpserver/public/404.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Not Found!</title>
</head>

<body>
    <h1>404 Error</h1>
    <p>Sorry the requested page does not exist</p>
</body>

</html>

httpserver/public/health.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Health!</title>
</head>

<body>
    <h1>Hello welcome to health page!</h1>
    <p>This site is perfectly fine</p>
</body>

</html>

httpserver/public/index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://www.cnblogs.com/QiaoPengjun/archive/2023/05/28/styles.css">
    <title>Index!</title>
</head>

<body>
    <h1>Hello, welcome to home page</h1>
    <p>This is the index page for the web site</p>
</body>

</html>

httpserver/public/styles.css

h1 {
    color: red;
    margin-left: 25px;
}

測驗該專案

運行

s1 on  master [?] via ?? 1.67.1 via ?? base 
? cargo run -p httpserver
   Compiling ryu v1.0.13
   Compiling itoa v1.0.6
   Compiling serde v1.0.163
   Compiling serde_json v1.0.96
   Compiling httpserver v0.1.0 (/Users/qiaopengjun/rust/s1/httpserver)
    Finished dev [unoptimized + debuginfo] target(s) in 2.48s
     Running `target/debug/httpserver`
Running on localhost:3000
Connection established
Connection established
Connection established
Connection established
Connection established
Connection established
Connection established

本文來自博客園,作者:QIAOPENGJUN,轉載請注明原文鏈接:https://www.cnblogs.com/QiaoPengjun/p/17437918.html

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/553633.html

標籤:其他

上一篇:Python 標準類別庫-因特網資料處理之Base64資料編碼

下一篇:返回列表

標籤雲
其他(159861) Python(38178) JavaScript(25460) Java(18141) C(15232) 區塊鏈(8268) C#(7972) AI(7469) 爪哇(7425) MySQL(7214) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5873) 数组(5741) R(5409) Linux(5343) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4577) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2434) ASP.NET(2403) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) .NET技术(1977) 功能(1967) Web開發(1951) HtmlCss(1948) C++(1924) python-3.x(1918) 弹簧靴(1913) xml(1889) PostgreSQL(1878) .NETCore(1862) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust Web 全堆疊開發之自建TCP、HTTP Server

    # Rust Web 全堆疊開發之自建TCP、HTTP Server ## 課程簡介 ### 預備知識 - Rust 編程語言入門 - https://www.bilibili.com/video/BV1hp4y1k7SV ### 課程主要內容 - WebService - 服務器端Web App - ......

    uj5u.com 2023-05-29 07:43:58 more
  • Python 標準類別庫-因特網資料處理之Base64資料編碼

    該模塊提供將二進制資料編碼為可列印ASCII字符并將這種編碼解碼回二進制資料的功能。它為[RFC 3548](https://tools.ietf.org/html/rfc3548.html)中指定的編碼提供編碼和解碼功能。定義了Base16、Base32和Base64演算法,以及事實上的標準Asci ......

    uj5u.com 2023-05-29 07:43:47 more
  • 關于STL容器的簡單總結

    # 關于STL容器的簡單總結 ## 1、結構體中多載運算子的示例 ``` //結構體小于符號的多載 struct buf { int a,b; bool operator queuea; //定義 a.push(x); //壓入 a.pop(); //彈出 a.size(); //取大小 a.fro ......

    uj5u.com 2023-05-29 07:43:38 more
  • 樹莓派使用HC-SR04超聲波測距

    ### 超聲波模塊介紹 超聲波測距原理很簡單: 1、通過記錄發送超聲波的時間、記錄超聲波回傳的時間,回傳時間與發送時間相減得到超聲波的持續時間。 2、通過公式:(**超聲波持續時間** * **聲波速度**) / **2**就可以得出距離; ![image.png](https://img2023. ......

    uj5u.com 2023-05-29 07:43:26 more
  • Python 使用ConfigParser操作ini組態檔

    ini 組態檔格式如下 要求:ini 檔案必須是GBK編碼,如果是UTF-8編碼,python讀取組態檔會報錯。 # 這里是注釋內容 # [FY12361] #婦幼保健介面服務埠 serverIP=192.168.1.11 serverPort=8400 [SM] #國產SM加密服務埠 se ......

    uj5u.com 2023-05-29 07:42:39 more
  • Python asyncio之協程學習總結

    ## 實踐環境 Python 3.6.2 ## 什么是協程 **協程**(Coroutine)一種電腦程式組件,該程式組件通過允許暫停和恢復任務,為非搶占式多任務生成子程式。**協程**也可以簡單理解為協作的程式,通過協同多任務處理實作并發的函式的變種(一種可以支持中斷的函式)。 下面,我們通過日常 ......

    uj5u.com 2023-05-29 07:42:28 more
  • 【python基礎】基本資料型別-字串型別

    # 1.初識字串 字串就是一系列字符。在python中,用引號括起來文本內容的都是字串。 其語法格式為:‘文本內容’或者“文本內容” 我們發現其中的引號可以是單引號,也可以是雙引號。這樣的靈活性可以使我們進行引號之間的嵌套。 撰寫程式如下所示: ![image](https://img2023 ......

    uj5u.com 2023-05-29 07:42:08 more
  • Python 標準類別庫-因特網資料處理之Base64資料編碼

    該模塊提供將二進制資料編碼為可列印ASCII字符并將這種編碼解碼回二進制資料的功能。它為[RFC 3548](https://tools.ietf.org/html/rfc3548.html)中指定的編碼提供編碼和解碼功能。定義了Base16、Base32和Base64演算法,以及事實上的標準Asci ......

    uj5u.com 2023-05-29 07:41:52 more
  • 樹莓派使用HC-SR04超聲波測距

    ### 超聲波模塊介紹 超聲波測距原理很簡單: 1、通過記錄發送超聲波的時間、記錄超聲波回傳的時間,回傳時間與發送時間相減得到超聲波的持續時間。 2、通過公式:(**超聲波持續時間** * **聲波速度**) / **2**就可以得出距離; ![image.png](https://img2023. ......

    uj5u.com 2023-05-29 07:41:37 more
  • 計算機網路面試八股文

    ## 網路分層結構 計算機網路體系大致分為三種,OSI七層模型、TCP/IP四層模型和五層模型。一般面試的時候考察比較多的是五層模型。最全面的Java面試網站:[最全面的Java面試網站](https://topjavaer.cn) ![](http://img.topjavaer.cn/img/t ......

    uj5u.com 2023-05-29 07:40:44 more