0

I wrote a simple code using cpprestsdk. I use a map (records) as a member of CommandHandler class, and manipulate it in a public method (has_record()).

it works before handler.open().wait() runs, but when I call it in a request, it crashes!

Here is my code:

#define BOOST_DATE_TIME_NO_LIB

#include <string>
#include <vector>
#include <cpprest/uri.h>
#include <cpprest/http_listener.h>
#include <cpprest/asyncrt_utils.h>

using namespace std;
using namespace web;
using namespace http;
using namespace utility;
using namespace http::experimental::listener;

class CommandHandler
{
public:
    CommandHandler(utility::string_t url);
    pplx::task<void> open() { return m_listener.open(); }
    pplx::task<void> close() { return m_listener.close(); }
    bool has_record();

private:
    std::map< std::string, unsigned int > records;
    void handle_get_or_post(http_request message);
    http_listener m_listener;
};
bool CommandHandler::has_record()
{
    return records.size() > 0 && records.find("1") != records.end();
}

CommandHandler::CommandHandler(utility::string_t url) : m_listener(url)
{
    m_listener.support(methods::GET, std::bind(&CommandHandler::handle_get_or_post, this, std::placeholders::_1));
    m_listener.support(methods::POST, std::bind(&CommandHandler::handle_get_or_post, this, std::placeholders::_1));
}

void CommandHandler::handle_get_or_post(http_request request)
{
    if(this->has_record())
        request.reply(status_codes::OK, 1);
    else
        request.reply(status_codes::OK, 0);
};


int main(int argc, char** argv)
{
    try
    {
        utility::string_t address = U("http://127.0.0.1:9595");
        uri_builder uri(address);
        auto addr = uri.to_uri().to_string();

        CommandHandler handler(addr);
        if(handler.has_record())
            std::cout<<"work!";
        handler.open().wait();

        ucout << utility::string_t(U("Listening for requests at: ")) << addr << std::endl;
        ucout << U("Press ENTER key to quit...") << std::endl;
        std::string line;
        std::getline(std::cin, line);

        handler.close().wait();
    }
    catch (std::exception& ex)
    {
        ucout << U("Exception: ") << ex.what() << std::endl;
        ucout << U("Press ENTER key to quit...") << std::endl;
        std::string line;
        std::getline(std::cin, line);
    }

    return 0;
}
JalalJaberi
  • 2,417
  • 8
  • 25
  • 41

1 Answers1

0

I found the problem but I don't understand why it throws. The problem is in this line of code:

request.reply(status_codes::OK, 0);

That 0 throws an exception

JalalJaberi
  • 2,417
  • 8
  • 25
  • 41