/
main_server.rs
163 lines (141 loc) · 4.74 KB
/
main_server.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#[global_allocator]
static ALLOC: snmalloc_rs::SnMalloc = snmalloc_rs::SnMalloc;
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::task::{Context, Poll};
use actix_codec::AsyncWrite;
use actix_http::{h1, Request};
use tokio_util::codec::Decoder;
use actix_rt::net::TcpStream;
use actix_server::Server;
use actix_service::fn_service;
use bytes::{Buf, BufMut, BytesMut};
use simd_json_derive::Serialize;
use tokio::io::{AsyncBufRead, BufReader};
mod models;
mod utils;
use crate::utils::Writer;
const HEAD_JSON: &[u8] =
b"HTTP/1.1 200 OK\r\nServer: A\r\nContent-Type: application/json\r\nContent-Length: 27\r\n";
const HEAD_PLAIN: &[u8] =
b"HTTP/1.1 200 OK\r\nServer: A\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n";
const HEAD_NOT_FOUND: &[u8] = b"HTTP/1.1 204 OK\r\nServer: A\r\n";
const BODY_PLAIN: &[u8] = b"Hello, World!";
const HDR_END: &[u8] = b"\r\n";
#[derive(Serialize)]
pub struct Message {
pub message: &'static str,
}
struct App {
io: BufReader<TcpStream>,
read_buf: BytesMut,
write_buf: BytesMut,
codec: h1::Codec,
}
impl App {
fn handle_request(&mut self, req: Request) {
match req.path() {
"/json" => {
let message = Message {
message: "Hello, World!",
};
self.write_buf.put_slice(HEAD_JSON);
self.codec
.config()
.write_date_header(&mut self.write_buf, false);
self.write_buf.put_slice(HDR_END);
message
.json_write(&mut Writer(&mut self.write_buf))
.unwrap();
}
"/plaintext" => {
self.write_buf.put_slice(HEAD_PLAIN);
self.codec
.config()
.write_date_header(&mut self.write_buf, false);
self.write_buf.put_slice(HDR_END);
self.write_buf.put_slice(BODY_PLAIN);
}
_ => {
self.write_buf.put_slice(HEAD_NOT_FOUND);
self.write_buf.put_slice(HDR_END);
}
}
}
}
impl Future for App {
type Output = Result<(), ()>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
loop {
if this.read_buf.capacity() - this.read_buf.len() < 512 {
this.read_buf.reserve(32_768);
}
let n = match Pin::new(&mut this.io).poll_fill_buf(cx) {
Poll::Pending => break,
Poll::Ready(Ok(filled)) => {
if filled.is_empty() {
return Poll::Ready(Ok(()));
}
this.read_buf.extend_from_slice(filled);
filled.len()
}
Poll::Ready(Err(_)) => return Poll::Ready(Err(())),
};
Pin::new(&mut this.io).consume(n);
}
if this.write_buf.capacity() - this.write_buf.len() <= 512 {
this.write_buf.reserve(32_768);
}
loop {
match this.codec.decode(&mut this.read_buf) {
Ok(Some(h1::Message::Item(req))) => this.handle_request(req),
Ok(None) => break,
_ => return Poll::Ready(Err(())),
}
}
if !this.write_buf.is_empty() {
let len = this.write_buf.len();
let mut written = 0;
while written < len {
match Pin::new(&mut this.io).poll_write(cx, &this.write_buf[written..]) {
Poll::Pending => {
break;
}
Poll::Ready(Ok(n)) => {
if n == 0 {
return Poll::Ready(Ok(()));
} else {
written += n;
}
}
Poll::Ready(Err(_)) => return Poll::Ready(Err(())),
}
}
if written == len {
unsafe { this.write_buf.set_len(0) }
} else if written > 0 {
this.write_buf.advance(written);
}
}
Poll::Pending
}
}
#[actix_web::main]
async fn main() -> io::Result<()> {
println!("Started HTTP server: 127.0.0.1:8080");
// start http server
Server::build()
.backlog(1024)
.bind("tfb-actix-server", "0.0.0.0:8080", || {
fn_service(|io: TcpStream| App {
io: BufReader::new(io),
read_buf: BytesMut::with_capacity(32_768),
write_buf: BytesMut::with_capacity(32_768),
codec: h1::Codec::default(),
})
})?
.run()
.await
}