Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple test of the experimental http_listener provided by the C++ REST SDK (Casablanca).
#define _CRT_SECURE_NO_DEPRECATE
#include <cpprest/http_listener.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <thread>
#include <chrono>
#include <ctime>
// cpprest provides macros for all streams but std::clog in basic_types.h
#ifdef _UTF16_STRINGS
// On Windows, all strings are wide
#define uclog std::wclog
#else
// On POSIX platforms, all strings are narrow
#define uclog std::clog
#endif // endif _UTF16_STRINGS
using namespace std;
using namespace web::http::experimental::listener;
using namespace web::http;
using namespace web;
void respond(const http_request& request, const status_code& status, const json::value& response) {
json::value resp;
resp[U("status")] = json::value::number(status);
resp[U("response")] = response;
// Pack in the current time for debugging purposes.
time_t now = time(0);
utility::stringstream_t ss;
ss << put_time(localtime(&now), L"%Y-%m-%dT%H:%S:%MZ");
resp[U("server_time")] = json::value::string(ss.str());
request.reply(status, resp);
}
int main()
{
// Synchronously bind the listener to all nics.
uclog << U("Starting listener.") << endl;
http_listener listener(U("http://*/json"));
listener.open().wait();
// Handle incoming requests.
uclog << U("Setting up JSON listener.") << endl;
listener.support(methods::GET, [] (http_request req) {
auto http_get_vars = uri::split_query(req.request_uri().query());
auto found_name = http_get_vars.find(U("request"));
if (found_name == end(http_get_vars)) {
auto err = U("Request received with get var \"request\" omitted from query.");
uclog << err << endl;
respond(req, status_codes::BadRequest, json::value::string(err));
return;
}
auto request_name = found_name->second;
uclog << U("Received request: ") << request_name << endl;
respond(req, status_codes::OK, json::value::string(U("Request received for: ") + request_name));
});
// Wait while the listener does the heavy lifting.
// TODO: Provide a way to safely terminate this loop.
uclog << U("Waiting for incoming connection...") << endl;
while(true) {
this_thread::sleep_for(chrono::milliseconds(2000));
}
// Nothing left to do but commit suicide.
uclog << U("Terminating JSON listener.") << endl;
listener.close();
return 0;
}
@maixuanhan
Copy link

maixuanhan commented Apr 8, 2016

Hi, does this code work?
I run with latest Casablanca v2.8.0, it throws exception at statement listener.open().wait();
Unhandled exception at 0x74EDDAD8 in StockServer.exe: Microsoft C++ exception: web::http::http_exception at memory location 0x0018F5F0.
Thanks


Updated!
I got the problem. It is because I ran the Visual Studio with normal privilege. Running VS with Administrator right resolved the problem.
Thanks for such a useful gist, Sean.

@draugvar
Copy link

draugvar commented Sep 12, 2017

any way to use this line under linux:
http_listener listener(U("http://*/json"));
i cannot access to any rest call. On windows it works.

@EdgarWahn
Copy link

EdgarWahn commented Mar 23, 2018

I tried to get something up with data in the URL we well and found an solution:
i.e. get param from www.example.com/api/native/foo/{param}/do

  • start the listener for /api/native/foo/
  • in the callback, get the full url (request.relative_uri().to_string()) and parse with std::regex.
    Assuming that I did not miss something, this task is solved way better and more comfortable in PHP Laravel...

@Nazar2
Copy link

Nazar2 commented Oct 1, 2020

use of undeclared identifier 'respond'

@samalitu
Copy link

samalitu commented Oct 29, 2021

Hello,
This might be a noobie question but what exactly is the purpose of the U function & where does it come from?

@SeanCline
Copy link
Author

SeanCline commented Oct 29, 2021

@samalitu That U() is specific to the C++ REST SDK.

First, some history...
On Windows, it's common to use wide strings. This is because Windows NT settled on 16-bit (wide) characters before UTF-8 gained traction. The C++ REST SDK builds on several operating systems, including Windows and Linux. The developers decided to keep using wide strings when building for Windows to so they don't need to do a conversion from UTF-8 for every system call. But on Linux-like OS's they can use UTF-8 (narrow) strings everywhere.

So, U() is just a macro. On Windows it expands to something like: #define U(x) L x but on Linux it's just #define U(x) x. This puts an L on the front of string literals when compiled on Windows, but leaves it alone with compiling on Linux.

This design is starting to feel more dated as Microsoft slowly starts recommending using UTF-8 in more places.

@mpanwar-github
Copy link

mpanwar-github commented May 11, 2022

Does it works for IPv6 for me "listener.open().wait();" is throwing below error.

terminate called after throwing an instance of 'boost::wrapexceptboost::system::system_error'
what(): resolve: Service not found

Using address as "http://[::1]:8585"

@SeanCline
Copy link
Author

SeanCline commented May 11, 2022

@mpanwar-github Hmm, it seems like a couple people have reported similar behaviour.

On my Windows box I also get an error when listening on an IPv6 address. When I listen on a wildcard address like http://*/json it listens on both IPv4 and IPv6, so that might be a workaround for you.

@mpanwar-github
Copy link

mpanwar-github commented May 12, 2022

@SeanCline Thanks for response, I have already tried with "*" that shows port listening on IPv6. I didn't find anything if this works for IPv6 at all.

Even i tried with interface as wel this was throwing below error.

Starting listener at url.http://[fe80::a3fe:944b:534f:7ec%enp44s0f1]:8585
terminate called after throwing an instance of 'web::uri_exception'
what(): Invalid hexadecimal digit

@mpanwar-github
Copy link

mpanwar-github commented May 12, 2022

further for me with hostname it is working not with IP "::1" that conclude that IPv6 support is there but format is different. Though i haven't done trying with other server IP with IPv6.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment