bobby 0.1.2

A minimal web framework.
Documentation
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use hyper::{header, service::service_fn};
use hyper_util::{
    rt::TokioIo,
    server::conn::auto::{self},
};
use log::{debug, error, info, trace, warn};
use std::{
    collections::HashMap,
    net::{IpAddr, SocketAddr},
    sync::Arc,
};
use tokio::net::TcpListener;

#[derive(Clone)]
struct TokioExecutor;

impl<F> hyper::rt::Executor<F> for TokioExecutor
where
    F: std::future::Future + Send + 'static,
    F::Output: Send + 'static,
{
    fn execute(&self, fut: F) {
        tokio::task::spawn(fut);
    }
}

impl TokioExecutor {
    pub fn new() -> Self {
        Self {}
    }
}

pub struct Request {
    method: hyper::Method,
    uri: hyper::Uri,
    params: HashMap<String, String>,
}

impl Request {
    pub fn new(request: &hyper::Request<hyper::body::Incoming>) -> Self {
        Request {
            method: request.method().clone(),
            uri: request.uri().clone(),
            params: HashMap::new(),
        }
    }

    pub fn method(&self) -> &hyper::Method {
        &self.method
    }

    pub fn uri(&self) -> &hyper::Uri {
        &self.uri
    }

    pub fn param(&self, name: &str) -> Option<&String> {
        self.params.get(name)
    }
}

pub enum ResponseError {
    CannotGetHeaders,
    InvalidHeaderName,
    InvalidHeaderValue,
    FailedToCreateHeader,
}

impl std::fmt::Display for ResponseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ResponseError::CannotGetHeaders => write!(f, "Cannot get response headers"),
            ResponseError::InvalidHeaderName => write!(f, "Invalid header name"),
            ResponseError::InvalidHeaderValue => write!(f, "Invalid header value"),
            ResponseError::FailedToCreateHeader => write!(f, "Failed to create header"),
        }
    }
}

impl std::fmt::Debug for ResponseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(self, f)
    }
}

impl std::error::Error for ResponseError {}

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

impl Response {
    pub fn html(body: impl Into<String>) -> Self {
        Response {
            body: body.into(),
            status: 200,
            headers: HashMap::from([(String::from("Content-Type"), String::from("text/html"))]),
        }
    }

    pub fn with_status(self, status: u16) -> Self {
        let mut response = self.clone();

        response.status = status;

        response
    }

    pub fn with_header(self, key: impl Into<String>, value: impl Into<String>) -> Self {
        let mut response = self.clone();

        response.headers.insert(key.into(), value.into());

        response
    }

    pub fn build(self) -> Result<hyper::Response<String>, ResponseError> {
        let mut builder = hyper::Response::builder().status(self.status);
        let headers = builder
            .headers_mut()
            .ok_or_else(|| ResponseError::CannotGetHeaders)?;

        // construct headers
        for (k, v) in self.headers.into_iter() {
            let header_name = header::HeaderName::from_bytes(k.as_bytes())
                .map_err(|_| ResponseError::InvalidHeaderName)?;

            let header_value =
                header::HeaderValue::from_str(&v).map_err(|_| ResponseError::InvalidHeaderValue)?;

            headers.insert(header_name, header_value);
        }

        // add content length
        headers.insert(
            header::HeaderName::from_static("content-length"),
            header::HeaderValue::from_str(&self.body.len().to_string())
                .map_err(|_| ResponseError::FailedToCreateHeader)?,
        );

        // add body and return
        Ok(builder.body(self.body).unwrap())
    }
}

#[derive(Clone)]
pub struct Route {
    method: hyper::Method,
    path: String,
    callable: fn(req: Request) -> Response,
}

#[derive(Clone)]
pub struct Bobby {
    ip: IpAddr,
    port: u16,
    routes: Vec<Route>,
}

impl Bobby {
    pub fn new() -> Bobby {
        Bobby {
            ip: IpAddr::from([127, 0, 0, 1]),
            port: 8080,
            routes: vec![],
        }
    }

    pub fn with_address(&mut self, ip: impl Into<IpAddr>, port: u16) {
        self.ip = ip.into();
        self.port = port;
    }

    pub fn get(&mut self, path: impl Into<String>, callable: fn(req: Request) -> Response) {
        self.routes.push(Route {
            method: hyper::Method::GET,
            path: path.into(),
            callable,
        });
    }

    pub fn post(&mut self, path: impl Into<String>, callable: fn(req: Request) -> Response) {
        self.routes.push(Route {
            method: hyper::Method::POST,
            path: path.into(),
            callable,
        });
    }

    pub fn put(&mut self, path: impl Into<String>, callable: fn(req: Request) -> Response) {
        self.routes.push(Route {
            method: hyper::Method::PUT,
            path: path.into(),
            callable,
        });
    }

    pub fn delete(&mut self, path: impl Into<String>, callable: fn(req: Request) -> Response) {
        self.routes.push(Route {
            method: hyper::Method::DELETE,
            path: path.into(),
            callable,
        });
    }

    pub fn patch(&mut self, path: impl Into<String>, callable: fn(req: Request) -> Response) {
        self.routes.push(Route {
            method: hyper::Method::PATCH,
            path: path.into(),
            callable,
        });
    }

    pub fn options(&mut self, path: impl Into<String>, callable: fn(req: Request) -> Response) {
        self.routes.push(Route {
            method: hyper::Method::OPTIONS,
            path: path.into(),
            callable,
        });
    }

    pub fn head(&mut self, path: impl Into<String>, callable: fn(req: Request) -> Response) {
        self.routes.push(Route {
            method: hyper::Method::HEAD,
            path: path.into(),
            callable,
        });
    }

    fn log_request(
        &self,
        request: &hyper::Request<hyper::body::Incoming>,
        level: log::Level,
        message: impl Into<String>,
    ) {
        let mut msg = message.into();

        if !msg.is_empty() {
            msg = format!(" - {}", msg);
        }

        match level {
            log::Level::Info => info!(
                "{http:?} {method} {path}{message}",
                http = request.version(),
                method = request.method(),
                path = request.uri(),
                message = msg
            ),
            log::Level::Warn => warn!(
                "{http:?} {method} {path}{message}",
                http = request.version(),
                method = request.method(),
                path = request.uri(),
                message = msg
            ),
            log::Level::Debug => debug!(
                "{http:?} {method} {path}{message}",
                http = request.version(),
                method = request.method(),
                path = request.uri(),
                message = msg
            ),
            log::Level::Trace => trace!(
                "{http:?} {method} {path}{message}",
                http = request.version(),
                method = request.method(),
                path = request.uri(),
                message = msg
            ),
            log::Level::Error => error!(
                "{http:?} {method} {path}{message}",
                http = request.version(),
                method = request.method(),
                path = request.uri(),
                message = msg
            ),
        }
    }

    fn uri_matches_path(&self, uri: &hyper::Uri, path: &str) -> bool {
        let path_parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
        let uri_parts: Vec<&str> = uri.path().split('/').filter(|s| !s.is_empty()).collect();

        if uri_parts.len() > path_parts.len() {
            return false;
        }

        for (i, path_part) in path_parts.iter().enumerate() {
            let is_param = path_part.starts_with('{') && path_part.ends_with('}');
            let is_optional_param = is_param && path_part.ends_with("?}");

            if i >= uri_parts.len() {
                return is_optional_param;
            }

            if !is_param && uri_parts[i] != *path_part {
                return false;
            }

            if is_param && !is_optional_param && uri_parts[i].is_empty() {
                return false;
            }
        }

        uri_parts.len() <= path_parts.len()
    }

    fn route(
        &self,
        _req: &hyper::Request<hyper::body::Incoming>,
    ) -> Result<hyper::Response<String>, ResponseError> {
        // attempt to find a matching route
        for route in &self.routes {
            if _req.method() == route.method && self.uri_matches_path(_req.uri(), &route.path) {
                let mut req = Request::new(_req);

                if let Some(params) = self.extract_params(_req.uri(), &route.path) {
                    req.params = params;
                }

                let response = (route.callable)(req);

                return response.build();
            }
        }

        // no matching route found
        self.log_request(_req, log::Level::Warn, "Not found");

        Response::html("Not found.").with_status(404).build()
    }

    fn extract_params(&self, uri: &hyper::Uri, path: &str) -> Option<HashMap<String, String>> {
        let path_parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
        let uri_parts: Vec<&str> = uri.path().split('/').filter(|s| !s.is_empty()).collect();
        let mut params = HashMap::new();

        for (i, path_part) in path_parts.iter().enumerate() {
            if path_part.starts_with('{') && path_part.ends_with('}') {
                let param_name = if path_part.ends_with("?}") {
                    &path_part[1..path_part.len() - 2]
                } else {
                    &path_part[1..path_part.len() - 1]
                };

                if i < uri_parts.len() {
                    params.insert(String::from(param_name), String::from(uri_parts[i]));
                }
            }
        }

        Some(params)
    }

    async fn listen(&self) {
        let addr = SocketAddr::from((self.ip, self.port));

        if let Ok(listener) = TcpListener::bind(addr).await {
            let bobby_arc = Arc::new(self.clone());

            loop {
                if let Ok((stream, _)) = listener.accept().await {
                    let io = TokioIo::new(stream);
                    let bobby = Arc::clone(&bobby_arc);

                    tokio::task::spawn(async move {
                        let service = service_fn(move |request| {
                            let bobby_ref = Arc::clone(&bobby);

                            async move {
                                bobby_ref.log_request(&request, log::Level::Info, "");
                                bobby_ref.route(&request)
                            }
                        });

                        if let Err(err) = auto::Builder::new(TokioExecutor::new())
                            .serve_connection(io, service)
                            .await
                        {
                            error!("Error: {}", err);
                        }
                    });
                } else {
                    error!("Could not start a listener.");
                }
            }
        } else {
            error!("Could not bind to configured address and port.");
        }
    }

    pub fn run(&self) {
        if let Ok(rt) = tokio::runtime::Runtime::new() {
            info!("Listening on {}:{} ...", self.ip, self.port);
            rt.block_on(self.listen());
        } else {
            error!("Could not start runtime.");
        }
    }
}