|
| 1 | +import std.stdio; |
| 2 | +import std.socket; |
| 3 | +import std.array; |
| 4 | + |
| 5 | +import asdf.serialization; |
| 6 | + |
| 7 | +import photon, photon.http; |
| 8 | + |
| 9 | +struct Message |
| 10 | +{ |
| 11 | + string message; |
| 12 | +} |
| 13 | + |
| 14 | +class BenchmarkProcessor : HttpProcessor { |
| 15 | + HttpHeader[] plainText = [HttpHeader("Content-Type", "text/plain; charset=utf-8")]; |
| 16 | + HttpHeader[] json = [HttpHeader("Content-Type", "application/json")]; |
| 17 | + Appender!(char[]) jsonBuf; |
| 18 | + this(Socket sock) { |
| 19 | + super(sock); |
| 20 | + jsonBuf = appender!(char[]); |
| 21 | + } |
| 22 | + |
| 23 | + override void handle(HttpRequest req) { |
| 24 | + if (req.uri == "/plaintext") { |
| 25 | + respondWith("Hello, world!", 200, plainText); |
| 26 | + } else if(req.uri == "/json") { |
| 27 | + jsonBuf.clear(); |
| 28 | + Message("Hello, World!").serializeToJsonPretty!""(jsonBuf); |
| 29 | + respondWith(jsonBuf.data, 200, json); |
| 30 | + } else { |
| 31 | + respondWith("Not found", 404, plainText); |
| 32 | + } |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +void server_worker(Socket client) { |
| 37 | + scope processor = new BenchmarkProcessor(client); |
| 38 | + try { |
| 39 | + processor.run(); |
| 40 | + } |
| 41 | + catch(Exception e) { |
| 42 | + debug stderr.writeln(e); |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +void server() { |
| 47 | + Socket server = new TcpSocket(); |
| 48 | + server.setOption(SocketOptionLevel.SOCKET, SocketOption.REUSEADDR, true); |
| 49 | + server.bind(new InternetAddress("0.0.0.0", 8080)); |
| 50 | + server.listen(1000); |
| 51 | + |
| 52 | + debug writeln("Started server"); |
| 53 | + |
| 54 | + void processClient(Socket client) { |
| 55 | + go(() => server_worker(client)); |
| 56 | + } |
| 57 | + |
| 58 | + while(true) { |
| 59 | + try { |
| 60 | + debug writeln("Waiting for server.accept()"); |
| 61 | + Socket client = server.accept(); |
| 62 | + debug writeln("New client accepted"); |
| 63 | + processClient(client); |
| 64 | + } |
| 65 | + catch(Exception e) { |
| 66 | + writefln("Failure to accept %s", e); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +void main() { |
| 72 | + startloop(); |
| 73 | + go(() => server()); |
| 74 | + runFibers(); |
| 75 | +} |
0 commit comments