PageRenderTime 82ms CodeModel.GetById 40ms app.highlight 9ms RepoModel.GetById 31ms app.codeStats 1ms

/mordor/examples/simpleappserver.cpp

http://github.com/mozy/mordor
C++ | 66 lines | 55 code | 10 blank | 1 comment | 12 complexity | c5de0c9ae9b90bc40aff2ea2d34be8c3 MD5 | raw file
 1// Copyright (c) 2010 - Mozy, Inc.
 2
 3#include "mordor/predef.h"
 4
 5#include <iostream>
 6
 7#include "mordor/config.h"
 8#include "mordor/http/server.h"
 9#include "mordor/iomanager.h"
10#include "mordor/main.h"
11#include "mordor/socket.h"
12#include "mordor/streams/memory.h"
13#include "mordor/streams/socket.h"
14#include "mordor/streams/transfer.h"
15
16using namespace Mordor;
17
18static std::map<URI, MemoryStream::ptr> g_state;
19
20static void httpRequest(HTTP::ServerRequest::ptr request)
21{
22    const std::string &method = request->request().requestLine.method;
23    const URI &uri = request->request().requestLine.uri;
24
25    if (method == HTTP::GET || method == HTTP::HEAD) {
26        std::map<URI, MemoryStream::ptr>::iterator it =
27            g_state.find(uri);
28        if (it == g_state.end()) {
29            HTTP::respondError(request, HTTP::NOT_FOUND);
30        } else {
31            MemoryStream::ptr copy(new MemoryStream(it->second->buffer()));
32            HTTP::respondStream(request, copy);
33        }
34    } else if (method == HTTP::PUT) {
35        MemoryStream::ptr stream(new MemoryStream());
36        transferStream(request->requestStream(), stream);
37        g_state[uri] = stream;
38        HTTP::respondError(request, HTTP::OK);
39    } else {
40        HTTP::respondError(request, HTTP::METHOD_NOT_ALLOWED);
41    }
42}
43
44MORDOR_MAIN(int argc, char *argv[])
45{
46    try {
47        Config::loadFromEnvironment();
48        IOManager ioManager;
49        Socket s(ioManager, AF_INET, SOCK_STREAM);
50        IPv4Address address(INADDR_ANY, 80);
51
52        s.bind(address);
53        s.listen();
54
55        while (true) {
56            Socket::ptr socket = s.accept();
57            Stream::ptr stream(new SocketStream(socket));
58            HTTP::ServerConnection::ptr conn(new HTTP::ServerConnection(stream,
59                &httpRequest));
60            conn->processRequests();
61        }
62    } catch (...) {
63        std::cerr << boost::current_exception_diagnostic_information() << std::endl;
64    }
65    return 0;
66}