octane 0.1.2

A web server built from the ground up.
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
404
405
406
use crate::constants::*;
#[cfg(feature = "cookies")]
use crate::cookies::Cookies;
use crate::deref;
use crate::path::is_ctl;
use crate::path::PathBuf;
use crate::util::Spliterator;
use std::cfg;
use std::collections::HashMap;
#[cfg(not(feature = "raw_headers"))]
use std::marker::PhantomData;
use std::str;

/// Holds the type of request method, like GET
/// POST etc. You don't need to use it directly
#[derive(Debug, PartialEq, Eq, Clone, Hash, Copy)]
pub enum RequestMethod {
    Options,
    Get,
    Head,
    Post,
    Put,
    Delete,
    Trace,
    Connect,
    All,
    None,
}

impl RequestMethod {
    /// Get all the values of the enum in an
    /// array. Useful for iterating and populating
    /// HashMap that holds closures for different
    /// different methods.
    pub fn values() -> [Self; 10] {
        use RequestMethod::*;
        [
            Options, Get, Head, Post, Put, Delete, Trace, Connect, All, None,
        ]
    }
    /// Return false if the RequestMethod has the
    /// variant `None` else return true
    pub fn is_some(&self) -> bool {
        if let Self::None = self {
            false
        } else {
            true
        }
    }
}
/// Holds the http versions you can match the
/// variants by doing a comparison with the version
/// in the request_line
///
/// # Example
///
/// ```no_run
/// use octane::server::Octane;
/// use octane::{route, router::{Flow, Route}};
/// use octane::request::HttpVersion;
///
/// let mut app = Octane::new();
/// app
/// .get("/",
///     route!(|req, res| {
///        if req.request_line.version == HttpVersion::Http11 {
///            // do something
///         }
///         Flow::Stop
///     }),
/// );
/// ```
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum HttpVersion {
    Http11,
    Http10,
    Http02,
    Http09,
    HttpInvalid,
}

impl HttpVersion {
    /// Returns the version in string like "1.1"
    /// or "1.0" etc
    pub fn get_version_string(self) -> String {
        match self {
            Self::Http11 => "1.1",
            Self::Http10 => "1.0",
            Self::Http09 => "0.9",
            Self::Http02 => "0.2",
            _ => "",
        }
        .to_owned()
    }
}
/// The RequestLine struct represents the first
/// line of the http request, which contains
/// the http version, path and method of request
///
/// # Example
///
/// ```no_run
/// use octane::server::Octane;
/// use octane::{route, router::{Flow, Route}};
/// use octane::request::RequestMethod;
///
/// let mut app = Octane::new();
/// app
/// .get("/",
///     route!(|req, res| {
///         assert_eq!(RequestMethod::Get, req.request_line.method);
///         Flow::Stop
///     }),
/// );
/// ```
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct RequestLine {
    pub method: RequestMethod,
    pub path: PathBuf,
    pub version: HttpVersion,
}

impl RequestLine {
    /// Parses a request line str and returns a
    /// request line struct. You don't have to
    /// ever use this directly.
    pub fn parse(request_line: &str) -> Option<Self> {
        let mut toks = request_line.split(SP);
        let method = toks.next()?;
        let path = match PathBuf::parse(toks.next()?) {
            Ok(val) => val,
            Err(e) => panic!("{:?}", e),
        };
        let version = toks.next()?;
        let (first, ver) = version.split_at(5);
        let enum_ver = match ver {
            "1.1" => HttpVersion::Http11,
            "1.0" => HttpVersion::Http10,
            "2.0" => HttpVersion::Http02,
            "0.9" => HttpVersion::Http09,
            _ => HttpVersion::HttpInvalid,
        };

        if cfg!(feature = "faithful") && (first != "HTTP/" || toks.next().is_some()) {
            return None;
        }
        let request_method = match method {
            "POST" => RequestMethod::Post,
            "GET" => RequestMethod::Get,
            "DELETE" => RequestMethod::Delete,
            "PUT" => RequestMethod::Put,
            "OPTIONS" => RequestMethod::Options,
            "HEAD" => RequestMethod::Head,
            "TRACE" => RequestMethod::Trace,
            "CONNECT" => RequestMethod::Connect,
            _ => RequestMethod::None,
        };
        Some(Self {
            method: request_method,
            path,
            version: enum_ver,
        })
    }
}

/// The header structure represents a parsed value
/// of unit header that looks like `key: value`
/// and holds the key and value both. You
/// shouldn't use it directly as the parsing has
/// been done for you and all the headers are
/// available in the `Headers` struct which you
/// get as a field in the `req` variable in
/// closures
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Header {
    pub name: String,
    pub value: String,
}

impl Header {
    /// Parses the `key: value` header unit
    /// str and returns a Header struct
    pub fn parse(header: String) -> Option<Self> {
        let mut toks = header.splitn(2, ':');
        let name = toks.next()?;
        if name.is_empty() {
            return None;
        }
        if cfg!(feature = "faithful") {
            for c in name.chars() {
                TOKEN_CHARS.get(&c)?;
            }
        }
        let value = toks.next()?.trim_start_matches(|c| c == SP || c == HT);
        if cfg!(feature = "faithful") && value.chars().any(is_ctl) {
            return None;
        }
        Some(Self {
            name: name.to_owned(),
            value: value.to_owned(),
        })
    }
}

/// The `Headers` struct holds _all_ the headers
/// a request might have in raw form (if the
/// feature is enabled) and in a HashMap with key
/// and value of the type `String`
///
/// # Example
///
/// ```no_run
/// use octane::server::Octane;
/// use octane::{route, router::{Flow, Route}};
/// use octane::request::RequestMethod;
///
/// let mut app = Octane::new();
/// app
/// .get("/",
///     route!(|req, res| {
///         let some_header = req.headers.get("HeaderName");
///         Flow::Stop
///     }),
/// );
/// ```
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Headers {
    pub parsed: HashMap<String, String>,
    #[cfg(feature = "raw_headers")]
    pub raw: Vec<Header>,
    #[cfg(not(feature = "raw_headers"))]
    pub raw: PhantomData<()>,
}

impl Headers {
    /// Parse all the headers on a request
    pub fn parse(request: String) -> Option<Self> {
        let toks = Spliterator::new(request.as_bytes(), B_CRLF);
        let mut headers: HashMap<String, String> = HashMap::new();
        #[cfg(feature = "raw_headers")]
        let mut raw_headers: Vec<Header> = Vec::new();
        for tok in toks {
            let parsed = Header::parse(match str::from_utf8(tok) {
                Ok(s) => s.to_owned(),
                Err(_) => return None,
            })?;
            headers
                .entry(parsed.name.to_ascii_lowercase())
                .and_modify(|v| *v = format!("{}, {}", v, parsed.value))
                .or_insert_with(|| parsed.value.to_owned());
            #[cfg(feature = "raw_headers")]
            raw_headers.push(parsed);
        }
        Some(Self {
            parsed: headers,
            #[cfg(feature = "raw_headers")]
            raw: raw_headers,
            #[cfg(not(feature = "raw_headers"))]
            raw: PhantomData,
        })
    }
}

pub fn parse_without_body(data: &str) -> Option<(RequestLine, Headers)> {
    let n = data.find("\r\n")?;
    let (line, rest) = data.split_at(n);
    let request_line = RequestLine::parse(line)?;
    let headers = Headers::parse((&rest[2..]).to_owned())?;
    Some((request_line, headers))
}

/// Represents a single request
///
/// # Example
///
/// ```no_run
/// use octane::server::Octane;
/// use octane::{route, router::{Flow, Route}};
/// use octane::request::RequestMethod;
///
/// let mut app = Octane::new();
/// app
/// .get("/",
///     route!(|req, res| {
///         // The req here is not actually a
///         // Request but a MatchedRequest which
///         // implements deref to Request.
///         // req.request is the Request,
///         // you can directly use Request methods
///         // req
///         Flow::Stop
///     }),
/// );
/// ```
///
/// The request struct holds cookies (if enabled
/// in features) headers, the request body, the
/// request_line
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Request<'a> {
    pub request_line: RequestLine,
    pub headers: Headers,
    pub body: &'a [u8],
    #[cfg(feature = "cookies")]
    pub cookies: Cookies,
}

impl<'a> Request<'a> {
    /// Parse a Request with request_line, headers
    /// and body and return a Request struct
    pub fn parse(request_line: RequestLine, headers: Headers, body: &'a [u8]) -> Option<Self> {
        #[cfg(feature = "cookies")]
        let cookies: Cookies;
        #[cfg(feature = "cookies")]
        if let Some(v) = headers.get("cookie") {
            cookies = Cookies::parse(v);
        } else {
            cookies = Default::default();
        }
        Some(Self {
            request_line,
            headers,
            #[cfg(feature = "cookies")]
            cookies,
            body,
        })
    }
}

/// The KeepAlive struct represents the value
/// parsed in the KeepAlive header. It holds the
/// timeout and max duration as a u64
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct KeepAlive {
    pub timeout: Option<u64>,
    pub max: Option<u64>,
}

impl KeepAlive {
    /// The parse method takes a single valid
    /// `Keep-Alive` header and parses it to
    /// return a KeepAlive struct
    pub fn parse(header: &str) -> Self {
        let mut ret = Self {
            timeout: None,
            max: None,
        };
        for tok in header.split(',') {
            let trimmed = tok.trim();
            let eq_ind = match trimmed.find('=') {
                Some(v) => v,
                None => continue,
            };
            let (name, val_str) = trimmed.split_at(eq_ind);
            let val: u64 = match (&val_str[1..]).parse() {
                Ok(v) => v,
                Err(_) => continue,
            };
            match name {
                "timeout" => ret.timeout = Some(val),
                "max" => ret.max = Some(val),
                _ => continue,
            };
        }
        ret
    }
}

/// The MatchedRequest is the struct which you see
/// when you have the `req` variable in the closure
/// It implements Deref to Request so you can use
/// Requet methods/properties directly on it
///
/// # Example
///
/// ```no_run
/// use octane::server::Octane;
/// use octane::{route, router::{Flow, Route}};
/// use octane::request::RequestMethod;
///
/// let mut app = Octane::new();
/// app
/// .get("/",
///     route!(|req, res| {
///         // The req here is not actually a
///         // Request but a MatchedRequest which
///         // implements deref to Request.
///         // You can just directly use Request
///         // methods on it
///         let header = req.headers.get("Some-Header");
///         Flow::Stop
///     }),
/// );
/// ```
/// The struct also have the values of the url
/// variables
/// TODO: Add a url variable example
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct MatchedRequest<'a> {
    pub request: Request<'a>,
    #[cfg(feature = "url_variables")]
    pub vars: HashMap<String, String>,
}

deref!(MatchedRequest<'a>, Request<'a>, request);
deref!(Headers, HashMap<String, String>, parsed);