dumb_cgi 0.8.0

An adequate, dependency-free CGI library for server-side CGI programs
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/*!
The two response types, `EmptyResponse` and `FullResponse`, to help build
(and deliver) responses to CGI requests.
*/

use std::collections::{hash_map::Entry, HashMap};
use std::io::Write;

/*
Internal value used to store `Response` header name-value pairs.

When a header is added to a `Response` (with one of several methods), a
lower-cased version of the passed name is used as a hash key, and the
unchanged version of the name is stored in a `HeaderValue`, along with the
value, of course. This is mainly to prevent the user from specifying
an incorrect value for `Content-length` (it can be easily overwritten
in the call to `.respond()` because the key is guaranteed to be the
all-lower-case `"content-length"`). It also prevents multiple header
specifications whose names differ by capitalization, which is maybe
not _wrong_, but is also probably not intentional.

According to [RFC2616](https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2),
headers with duplicate names _are_ allowed; however,

```text
Header-name: value0
Header-name: value1
```

is equivalent to

```text
Header-name: value0, value1
```

So multiple insertions of the same header will map the former form to
the latter form.

This is also important, because according to that same RFC, the order
in which these multiple values occur might matter. Because `dumb_cgi`
sends response headers by iterating through a `HashMap` (which does
_not_ guarantee any ordering), this rearrangement also guarantees
multiple values appear in the same order they are added.
*/
#[derive(Debug, Clone)]
struct HeaderValue {
    name: String,
    value: String,
}

/**
A response with no body.

Both `EmptyResponse::new()` and `FullResponse::new()` create values of this
type. Until the `.with_content_type()` method is called (consuming its
receiver and returning a `FullResponse`), a response may not have a body
added or bytes written to its body.
*/
#[derive(Debug)]
pub struct EmptyResponse {
    status: u16,
    headers: HashMap<String, HeaderValue>,
}

impl EmptyResponse {
    /**
    Create a new, headerless, empty response with the given HTTP status code.

    Headers can be set, and a body can be added, using the builder pattern:

    ```rust
    # use dumb_cgi::EmptyResponse;
    // Responding to a CORS preflight request
    let r = EmptyResponse::new(204)
        .with_header("Access-Control-Allow-Methods", "GET, POST")
        .with_header("Access-Control-Allow-Origin", "https://this-origin.net")
        .with_header("Access-Control-Allow-Headers", "Content-type");
    ```
    */
    pub fn new(status: u16) -> EmptyResponse {
        EmptyResponse {
            status,
            headers: HashMap::new(),
        }
    }

    /**
    Adds a response header.

    Adding multiple headers with the same name will concatenate the added
    values in a comma-separated list:

    ```rust
    # use dumb_cgi::EmptyResponse;
    let mut r = EmptyResponse::new(200);
    r.add_header("Custom-header", "value0");
    r.add_header("Custom-header", "value1");

    assert_eq!(r.get_header("Custom-header"), Some("value0, value1"));
    ```
    */
    pub fn add_header<N, V>(&mut self, name: N, value: V)
    where
        N: Into<String>,
        V: Into<String>,
    {
        let name = name.into();
        let value = value.into();
        let name_key = (&name).to_lowercase();
        match self.headers.entry(name_key) {
            Entry::Occupied(mut oe) => {
                let old = oe.get_mut();
                (*old).value.push_str(", ");
                (*old).value.push_str(&value);
            }
            Entry::Vacant(ve) => {
                let header = HeaderValue { name, value };
                ve.insert(header);
            }
        }
    }

    /**
    Builder pattern method for adding a header value.

    Works similarly to `.add_header()`:

    ```rust
    # use dumb_cgi::EmptyResponse;
    let r = EmptyResponse::new(200)
        .with_header("Custom-header", "value0")
        .with_header("Custom-header", "value1");

    assert_eq!(r.get_header("custom-header"), Some("value0, value1"));
    ```
    */
    pub fn with_header<N, V>(self, name: N, value: V) -> EmptyResponse
    where
        N: Into<String>,
        V: Into<String>,
    {
        let mut new = self;
        new.add_header(name, value);
        new
    }

    /**
    Adds a `Content-type` header to this request, turning it into a
    `FullResponse`, which can have a body.

    Any `content-type` header explicitly set with the `.with_header()` or
    `.add_header()` methods will be overwritten and replaced with this
    value when the request is sent.

    ```rust
    # use dumb_cgi::EmptyResponse;
    let r = EmptyResponse::new(400)
        .with_content_type("test/plain")
        .with_body("Your request must contain a \"Content=type\" header.");
    ````
    */
    pub fn with_content_type<T>(self, content_type: T) -> FullResponse
    where
        T: Into<String>,
    {
        FullResponse {
            status: self.status,
            headers: self.headers,
            content_type: content_type.into(),
            body: Vec::new(),
        }
    }

    /// Return the HTTP status code associated with this response.
    pub fn get_status(&self) -> u16 {
        self.status
    }

    /// Change the HTTP status code associated with this response.
    pub fn set_status(&mut self, new_status: u16) {
        self.status = new_status;
    }

    /// Return the header value associated with the header `name` (if set).
    pub fn get_header<T: AsRef<str>>(&self, name: T) -> Option<&str> {
        let name = name.as_ref().to_lowercase();
        self.headers.get(&name).map(|s| s.value.as_str())
    }

    /**
    Write this response to stdout. This consumes the value.

    ```rust
    # use dumb_cgi::EmptyResponse;
    let r = EmptyResponse::new(204)
        .with_header("Status-Message", "success")
        .with_header("Cache-Control", "no-store");

    r.respond().unwrap();
    ```
    */
    pub fn respond(mut self) -> std::io::Result<()> {
        let status_str = format!("{}", &self.status);
        let status_header = HeaderValue {
            name: "Status".to_owned(),
            value: status_str,
        };
        _ = self.headers.insert("status".to_owned(), status_header);

        let stdout = std::io::stdout();
        let mut out = stdout.lock();
        for (_, header) in self.headers.iter() {
            write!(&mut out, "{}: {}\r\n", &header.name, &header.value)?;
        }

        write!(&mut out, "\r\n")
    }
}

/**
A response with a body, instantiated by calling `.with_content_type()`
on an `EmptyResponse`.

Note that there is no `FullResponse::new()` associated function, and that
the only way to get a `FullResponse` is by adding a content type to an
`EmptyResponse` with the `.with_content_type()` method.

```rust
# use dumb_cgi::EmptyResponse;
let r = EmptyResponse::new(200)                 // an `EmptyResponse` upon instantiation
    .with_header("Cache-Control", "no-store")  // still an `EmptyResponse`
    .with_content_type("text/json")            // now a `FullResponse`
    .with_body("{\"status\":\"updated\"}");

r.respond().unwrap();
```

`FullResponse` also implements `std::io::Write` for writing to the body:

```rust
# use dumb_cgi::EmptyResponse;
# use std::io::Write;
let mut r = EmptyResponse::new(200)
    .with_content_type("text/plain");

let status = r.get_status();

write!(&mut r, "This is the body of the response.\n").unwrap();
write!(&mut r, "The status is {}.", &status).unwrap();

r.respond().unwrap();
```
*/

#[derive(Debug)]
pub struct FullResponse {
    status: u16,
    headers: HashMap<String, HeaderValue>,
    body: Vec<u8>,
    content_type: String,
}

impl FullResponse {
    /**
    Adds a response header.

    Adding multiple headers with the same name will concatenate the added
    values in a comma-separated list:

    ```rust
    # use dumb_cgi::EmptyResponse;
    let mut r = EmptyResponse::new(200).with_content_type("text/plain");
    r.add_header("Custom-header", "value0");
    r.add_header("Custom-header", "value1");

    assert_eq!(r.get_header("Custom-header"), Some("value0, value1"));
    ```
    */
    pub fn add_header<N, V>(&mut self, name: N, value: V)
    where
        N: Into<String>,
        V: Into<String>,
    {
        let name = name.into();
        let value = value.into();
        let name_key = (&name).to_lowercase();
        match self.headers.entry(name_key) {
            Entry::Occupied(mut oe) => {
                let old = oe.get_mut();
                (*old).value.push_str(", ");
                (*old).value.push_str(&value);
            }
            Entry::Vacant(ve) => {
                let header = HeaderValue { name, value };
                ve.insert(header);
            }
        }
    }

    /**
    Builder pattern method for adding a header value.

    Works similarly to `.add_header()`:

    ```rust
    # use dumb_cgi::EmptyResponse;
    let r = EmptyResponse::new(200)
        .with_content_type("test/plain")
        .with_header("Custom-header", "value0")
        .with_header("Custom-header", "value1");

    assert_eq!(r.get_header("custom-header"), Some("value0, value1"));
    ```
    */
    pub fn with_header<N, V>(self, name: N, value: V) -> FullResponse
    where
        N: Into<String>,
        V: Into<String>,
    {
        let mut new = self;
        new.add_header(name, value);
        new
    }

    /**
    Builder-pattern method for adding a body.

    This replaces any current body value with `new_body`:

    ```rust
    # use dumb_cgi::EmptyResponse;
    let r = EmptyResponse::new(200)
        .with_content_type("text/plain")
        .with_body("This is the first body.")
        .with_body("This is the second body.");

    assert_eq!(r.get_body(), "This is the second body.".as_bytes());
    ```
    */
    pub fn with_body<T: Into<Vec<u8>>>(self, new_body: T) -> FullResponse {
        let mut new = self;
        new.body = new_body.into();
        new
    }

    /// Return the HTTP status code associated with this response.
    pub fn get_status(&self) -> u16 {
        self.status
    }

    /// Change the HTTP status code associated with this response.
    pub fn set_status(&mut self, new_status: u16) {
        self.status = new_status;
    }

    /// Return the header value associated with the header `name` (if set).
    pub fn get_header<T: AsRef<str>>(&self, name: T) -> Option<&str> {
        let name = name.as_ref().to_lowercase();
        self.headers.get(&name).map(|s| s.value.as_str())
    }

    /// Return a reference to the current body payload.
    pub fn get_body(&self) -> &[u8] {
        &self.body
    }

    /**
    Write this response to stdout. This consumes the value.

    ```rust
    # use dumb_cgi::EmptyResponse;
    let body: &str = "<!doctype html>
    <html>
    <head>
        <meta charset='utf-8'>
    </head>
    <body>
        <h1>Hello, browser!</h1>
    </body>
    </html>";

    let r = EmptyResponse::new(200)
        .with_content_type("text/html")    // this makes it a `FullResponse`
        .with_body(body);

    r.respond().unwrap();
    ```
    */
    pub fn respond(mut self) -> std::io::Result<()> {
        let status_str = format!("{}", &self.status);
        self.add_header("Status".to_owned(), status_str);
        if !self.body.is_empty() {
            self.add_header("Content-type".to_owned(), self.content_type.clone());
            self.add_header("Content-length".to_owned(), format!("{}", self.body.len()));
        }

        let stdout = std::io::stdout();
        let mut out = stdout.lock();

        for (_, header) in self.headers.iter() {
            write!(&mut out, "{}: {}\r\n", &header.name, &header.value)?;
        }
        write!(&mut out, "\r\n")?;

        if !self.body.is_empty() {
            out.write_all(&self.body)?;
        }

        Ok(())
    }
}

/// `Write` is implemented for `FullResponse` by appending to the `.body`
/// vector, in exactly the same way it's implemented for `Vec<u8>`.
impl Write for FullResponse {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.body.extend_from_slice(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}