Crates.io | wenmeng |
lib.rs | wenmeng |
version | 0.2.7 |
source | src |
created_at | 2023-09-16 09:00:50.878769 |
updated_at | 2024-02-27 06:46:08.543099 |
description | a http server for rust |
homepage | |
repository | https://github.com/tickbh/wenmeng |
max_upload_size | |
id | 974232 |
size | 374,797 |
一个包含http1.1及http2的服务器及客户端的实现, 依赖tokio实现
简单的hello world示例
use std::{env, error::Error};
use tokio::net::TcpListener;
use webparse::{Request, Response};
use wenmeng::{self, ProtResult, RecvStream, Server, RecvRequest};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let addr = env::args()
.nth(1)
.unwrap_or_else(|| "127.0.0.1:8080".to_string());
let server = TcpListener::bind(&addr).await?;
println!("Listening on: {}", addr);
loop {
let (stream, _) = server.accept().await?;
tokio::spawn(async move {
let mut server = Server::new(stream);
async fn operate(req: RecvRequest) -> ProtResult<Option<Response<String>>> {
let response = Response::builder()
.version(req.version().clone())
.body("Hello World".to_string())?;
Ok(Some(response))
}
let _ = server.incoming(operate).await;
});
}
}
http1/http2通用, recv可以接收多个返回及服务端的推送信息
use webparse::Request;
use wenmeng::{Client, ProtResult};
async fn test_http2() -> ProtResult<()> {
let url = "http://nghttp2.org/"; //"http://127.0.0.1:8080/"
let req = Request::builder().method("GET").url(url).body("").unwrap();
let client = Client::builder().connect(url).await.unwrap();
let (mut recv, sender) = client.send2(req.into_type()).await?;
let mut res = recv.recv().await.unwrap();
res.body_mut().wait_all().await;
println!("res = {}", res);
let req = Request::builder()
.method("GET")
.url(url.to_owned() + "blog/")
.body("")
.unwrap();
sender.send(req.into_type()).await?;
let res = recv.recv().await.unwrap();
println!("res = {}", res);
Ok(())
}
Apache License, Version 2.0 (LICENSE-APACHE or https://apache.org/licenses/LICENSE-2.0)