1 /**
2  * Start a HTTP server on a port and serve the files in the current directory.
3  *
4  * License:
5  *   This Source Code Form is subject to the terms of
6  *   the Mozilla Public License, v. 2.0. If a copy of
7  *   the MPL was not distributed with this file, You
8  *   can obtain one at http://mozilla.org/MPL/2.0/.
9  *
10  * Authors:
11  *   Vladimir Panteleev <vladimir@thecybershadow.net>
12  */
13 
14 module ae.demo.http.httpserve;
15 
16 import std.stdio;
17 import std.conv;
18 import std.datetime;
19 import std.exception;
20 import std.string;
21 
22 import ae.sys.log;
23 import ae.sys.shutdown;
24 import ae.net.http.server;
25 import ae.net.http.common;
26 import ae.net.http.responseex;
27 import ae.net.ietf.headers;
28 import ae.net.asockets;
29 
30 class FileServer
31 {
32 	HttpServer server;
33 
34 	this(ushort port)
35 	{
36 		server = new HttpServer();
37 		server.log = new ConsoleLogger("Web");
38 		server.handleRequest = &onRequest;
39 		port = server.listen(port);
40 		addShutdownHandler({ server.close(); });
41 	}
42 
43 	void onRequest(HttpRequest request, HttpServerConnection conn)
44 	{
45 		auto response = new HttpResponseEx();
46 		response.status = HttpStatusCode.OK;
47 
48 		try
49 			response.serveFile(
50 				decodeUrlParameter(request.resource[1..$]),
51 				"",
52 				true,
53 				formatAddress("http", conn.localAddress, request.host, request.port) ~ "/");
54 		catch (Exception e)
55 			response.writeError(HttpStatusCode.InternalServerError, e.msg);
56 		conn.sendResponse(response);
57 	}
58 }
59 
60 void main(string[] args)
61 {
62 	new FileServer(args.length > 1 ? to!ushort(args[1]) : 0);
63 	socketManager.loop();
64 }