这是我第一次使用restbed或与HTTP相关的任何东西(编程明智)。 所以我将restbed添加到我的项目中并尝试运行restbed的github主页中显示的简单示例。
#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( );
int content_length = request->get_header( "Content-Length", 0 );
session->fetch( content_length, [ ]( 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" } } );
} );
}
int main( const int, const char** )
{
auto resource = make_shared< Resource >( );
resource->set_path( "/resource" );
resource->set_method_handler( "POST", post_method_handler );
auto settings = make_shared< Settings >( );
settings->set_port( 1984 );
settings->set_default_header( "Connection", "close" );
Service service;
service.publish( resource );
service.start( settings );
return EXIT_SUCCESS;
}
它在行中停止:service.start(settings);
我已经检查了start函数,使用了某种singnal处理程序,但我不知道测试应该如何工作。
有人可以帮助我理解我是否做错了,测试是按预期工作还是其他任何事情?
感谢。
编辑:这个解释帮了很多忙。所以我尝试了你发布的代码并得到了这个:
$> curl -w'\n' -v -X GET 'http://localhost:1984/resource'
* Hostname was NOT found in DNS cache
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 1984 (#0)
> GET /resource HTTP/1.1
> User-Agent: curl/7.35.0
> Host: localhost:1984
> Accept: */*
>
< HTTP/1.1 501 Not Implemented
* no chunk, no close, no size. Assume close to signal end
<
* Closing connection 0
我猜测“未实现”消息不是一件好事。你能帮我解决这个问题吗?
答案 0 :(得分:3)
Service :: start处理程序正在阻塞。调用此方法的线程将用于处理传入的请求。
如果您希望继续处理,请设置ready handler。当服务启动并准备好处理请求时,将调用此处理程序。
服务器强>
#include <thread>
#include <memory>
#include <chrono>
#include <cstdlib>
#include <restbed>
using namespace std;
using namespace restbed;
void get_method_handler( const shared_ptr< Session > session )
{
session->close( OK, "Hello, World!", { { "Content-Length", "13" }, { "Connection", "close" } } );
}
void service_ready_handler( Service& )
{
fprintf( stderr, "Hey! The service is up and running." );
}
int main( const int, const char** )
{
auto resource = make_shared< Resource >( );
resource->set_path( "/resource" );
resource->set_method_handler( "GET", get_method_handler );
auto settings = make_shared< Settings >( );
settings->set_port( 1984 );
auto service = make_shared< Service >( );
service->publish( resource );
service->set_ready_handler( service_ready_handler );
service->start( settings );
return EXIT_SUCCESS;
}
<强>客户端强>
curl -w'\n' -v -X GET 'http://localhost:1984/resource'