gpt4 book ai didi

c++ - 如何实现一个 REST API 服务器?

转载 作者:IT老高 更新时间:2023-10-28 22:39:09 32 4
gpt4 key购买 nike

我是一名具有中级 C++ 编程经验的大学生。 我想尽快为我的应用程序实现一个简单的基于 REST 的 API。

我看过 CasablancalibWebSockets但是在他们各自的网站上发布的例子有点让我头疼。是否有任何库有更多面向初学者的关于在 C++ 中创建 RESTFUL API 服务器的教程?

注意:我知道这个问题已经在 C# 中被问过几次,但答案已经超过一两年了,而且大多不是针对初学者的。我希望新的帖子能带来一些新的答案!

最佳答案

Restbed通过ASIO 提供异步客户端/服务器功能和 C++11。我们有很多 examples对于不喜欢阅读头文件的人,我们将很快提供文档。

#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 = 0;
request->get_header( "Content-Length", content_length );

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;
}

下一个主要功能将允许依赖注入(inject)应用程序层。

auto settings = make_shared< Settings >( );

Service service;
service.add_application_layer( http_10_instance );
service.add_application_layer( http_11_instance );
service.add_application_layer( http2_instance );
service.add_application_layer( spdy_instance );
service.start( settings );

关于c++ - 如何实现一个 REST API 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32017457/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com