1 module handy_httpd;
2 
3 public import handy_httpd.server;
4 public import handy_httpd.request;
5 public import handy_httpd.response;
6 public import handy_httpd.handler;
7 public import handy_httpd.handlers;
8 public import handy_httpd.responses;
9 
10 /** 
11  * General-purpose testing for the HTTP server and its behavior.
12  */
13 unittest {
14     import std.stdio;
15     import core.thread;
16     import core.time;
17     const ushort PORT = 45_312;
18 
19     /** 
20      * Helper function to prepare an HTTP server for testing.
21      * Returns: A simple HTTP server for testing.
22      */
23     HttpServer getSimpleServer() {
24         auto s = new HttpServer(
25             simpleHandler((request) {
26                 if (request.method == "GET") {
27                     return okResponse().setBody("Hello world!");
28                 } else {
29                     return methodNotAllowed();
30                 }
31             }),
32             "127.0.0.1",
33             PORT,
34             8192,
35             true
36         );
37         // Start up the server in its own thread.
38         new Thread(() {s.start();}).start();
39         return s;
40     }
41 
42     // Test that the server can start up and shut down properly.
43     auto s = getSimpleServer();
44     while (!s.isReady) {
45         writeln("Waiting for server to be ready...");
46         Thread.sleep(msecs(10));
47     }
48     assert(s.isReady);
49 
50     import std.net.curl;
51     import std.string;
52     import std.exception;
53     string url = std..string.format!"http://localhost:%d"(PORT);
54     
55     assert(get(url) == "Hello world!");
56     assertThrown!CurlException(post(url, ["hello"]));
57 
58     // Test parallel request handling.
59     for (int i = 0; i < 10; i++) {
60         new Thread(() {
61             auto c = HTTP();
62             assert(get(url, c) == "Hello world!");
63         }).start();
64     }
65 
66     s.stop();
67 }