1 module app;
2 
3 import core.time;
4 import vibe.core.log;
5 import vibe.core.core : exitEventLoop, runApplication, runTask, sleep;
6 import vibe.http.client;
7 import vibe.http.server;
8 import vibe.stream.operations : readAllUTF8;
9 
10 void handleRequest(scope HTTPServerRequest req, scope HTTPServerResponse res)
11 {
12 	res.statusCode = HTTPStatus.ok;
13 	res.writeBody("Hello, World!", "text/plain");
14 }
15 
16 void main()
17 {
18 	immutable string xforward_addr = "127.0.0.2";
19 	immutable string xforward_addrs = xforward_addr ~ ", 127.0.0.3";
20 
21 	bool delegate (in NetworkAddress address) @safe nothrow rejectDg = (in address) @safe nothrow {
22 		return (address.toAddressString == xforward_addr);
23     };
24 
25 	auto settings = new HTTPServerSettings;
26 	settings.port = 8099;
27 	settings.rejectConnectionPredicate = rejectDg;
28 	settings.bindAddresses = ["::1", "127.0.0.1"];
29 
30 	auto l = listenHTTP(settings, &handleRequest);
31 	scope (exit) l.stopListening();
32 
33 	runTask({
34 		bool got403, got403_multiple, got200;
35 		scope (exit) exitEventLoop();
36 
37 		try {
38 			requestHTTP("http://127.0.0.1:8099/",
39 				(scope req) {
40 					req.headers["X-Forwarded-For"] = xforward_addr;
41 				},
42 				(scope res) {
43 					got403 = (res.statusCode == HTTPStatus.forbidden);
44 				}
45 			);
46 			requestHTTP("http://127.0.0.1:8099/",
47 				(scope req) {
48 					req.headers["X-Forwarded-For"] = xforward_addrs;
49 				},
50 				(scope res) {
51 					got403_multiple = (res.statusCode == HTTPStatus.forbidden);
52 				}
53 			);
54 			requestHTTP("http://127.0.0.1:8099/", null,
55 				(scope res) {
56 					got200 = (res.statusCode == HTTPStatus.ok);
57 				}
58 			);
59 		} catch (Exception e) assert(false, e.msg);
60 		assert(got403, "Status 403 wasn't received");
61 		assert(got403_multiple, "Status 403 wasn't received for multiple addresses");
62 		assert(got200, "Status 200 wasn't received");
63 		logInfo("All web tests succeeded.");
64 	});
65 
66 	runApplication();
67 }