当前位置: 首页 > 工具软件 > Restbed > 使用案例 >

restbed -C++ restfull 架构的应用 http

澹台冯浩
2023-12-01
#include <ros/ros.h>
#include <string>
#include <memory>
#include <cstdlib>
#include <fstream>
#include <restbed>
#include <streambuf>

using namespace std;
using namespace restbed;

void get_method_handler( const shared_ptr< Session > session)
{
    const auto request = session->get_request();
    const string filename = request->get_path_parameter("filename");

    ifstream stream("/home/tmp/index.html", ifstream::in);

    if(stream.is_open())
    {
        ROS_INFO("open file ok !");
        const string body = string( istreambuf_iterator<char>(stream), istreambuf_iterator<char >());

        const multimap<string, string> headers
        {
            {"Content-Type", "text/html"},
            {"Content-Length", ::to_string(body.length())}
        };

        session->close(OK, body, headers);
    }else
    {
        session->close( NOT_FOUND );
    }

}


int main(int argc, char **argv)
{
    ros::init(argc, argv, "test_carema");
    ros::NodeHandle nh;
    ros::Rate loop_rate(1.0);
    ROS_INFO_STREAM("Hello, ROS!");

    auto resource = std::make_shared< Resource >();
    resource->set_path("/static/index.html");
    resource->set_method_handler("GET", get_method_handler);

    auto settings = std::make_shared< Settings >();
    settings->set_port(1984);
    settings->set_default_header("Connection", "close");

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

    ros::MultiThreadedSpinner spinner(0);
    spinner.spin();

    return 0;
}
 类似资料: