Skip to content

Instantly share code, notes, and snippets.

@RoyBellingan
Created February 21, 2021 00:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RoyBellingan/ba9a1ab6af13f8a0a2970fbe74d1e3c9 to your computer and use it in GitHub Desktop.
Save RoyBellingan/ba9a1ab6af13f8a0a2970fbe74d1e3c9 to your computer and use it in GitHub Desktop.
post.md

Overview

"A web service is a service offered by an electronic device to another electronic device, communicating with each other via the World Wide Web. In a web service, the Web technology such as HTTP—originally designed for human-to-machine communication—is utilized for machine-to-machine communication, more specifically for transferring machine-readable file formats such as XML and JSON." -- Wikipedia

Example

#include <memory>
#include <cstdlib>
#include <restbed>

using namespace std;
using namespace restbed;

void post_method_handler( const shared_ptr< Session > session )
{
    const auto request = session->get_request( );

    size_t content_length = request->get_header( "Content-Length", 0 );

    //This is an async operation, so will be scheduled to be performed AFTER the post data is ready
    session->fetch( content_length, [ request ]( const shared_ptr< Session > session, const Bytes & body )
    {
        fprintf( stdout, "%.*s\n", ( int ) body.size( ), body.data( ) );
        session->close( OK, "Hello, World!", { { "Content-Length", "13" }, { "Connection", "close" } } );
    } );
    //Function will now return, and depending on the post size the lambda is probably still scheduled to be executed!
}

int main( const int, const char** )
{
    auto resource = make_shared< Resource >( );
    resource->set_path( "/resource" );
    resource->set_method_handler( "POST", post_method_handler );

    Service service;
    service.publish( resource );
    service.start( );

    return EXIT_SUCCESS;
}

Build

$ clang++ -o example example.cpp -l restbed

Execution

$ ./example

$ curl -w'\n' -v -X POST --data 'Hello, Restbed' 'http://localhost/resource'

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