반응형

[참조] https://codingschool.tistory.com/4

 

c++ Restful API 서버 만들기

 

정리. 수알치 오상문 

 

자세한 내용은 위 참조 링크에 방문해서 확인하시기 바랍니다.

 

RestBed

Restbed는 RESTful API Server 애플리케이션을 구축하기 위한 C++11 라이브러리입니다.

 

- HTTP 요청 및 응답 처리

- JSON 구문 분석 및 직렬화

- 비동기, 연결 풀링 등 제공

- RESTful API를 구축하기 위한 제반 기능

- 다양한 운영체제 지원(Cross Flatform) : Windows, macOS, Linux 등 지원

- 인증, 속도 제한 및 로깅 기능 추가 가능

 

설치

소스코드 다운로드 : Restbed용 소스코드는 github에서 다운로드 할 수 있습니다.

https://github.com/Corvusoft/restbed

 

라이브러리 빌드 : 다음 명령을 실행하여 소스 코드를 라이브러리로 만듭니다.

git clone https://github.com/corvusoft/restbed.git
mkdir restbed/build
cd restbed/build
cmake [-DBUILD_SSL=NO] [-DBUILD_TESTS=NO] ..
make install
make test

 

[참고] Windows 환경에서는 빌드보다 vpckg 설치가 더 편함

git clone https://github.com/Microsoft/vcpkg.git

cd vcpkg

./bootstrap-vcpkg.sh

./vcpkg integrate install

./vcpkg install restbed

 

첫 예제

/post/v1/resource  
/post/v1/about 

8080 포트 사용

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

using namespace std;
using namespace restbed;

// resource handler 함수
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" } } );
    } );
}

// resource2 handler 함수 (파라미터는 동일)
void post_method_handler2( 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** )
{
	// URL 별로 resource 객체 생성
    auto resource = make_shared< Resource >( );
    resource->set_path( "/post/v1/resource" );
    resource->set_method_handler( "POST", post_method_handler );
    
    auto resource2 = make_shared< Resource >( );
    resource2->set_path( "/post/v1/about" );
    resource2->set_method_handler( "POST", post_method_handler2 );

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

    Service service;
    // 생성된 모든 resource는 반드시 publish 해야 동작
    service.publish( resource );
    service.publish( resource2 );
    service.start( settings );

    return EXIT_SUCCESS;
}

 

API 경로 별로 Handler 함수를 등록합니다.

예제와 다르게 서비스 구현시 Handler 함수는 별도 소스 파일에 작성하는 게 유지보수에 좋습니다.

 

두 번째 예제

WildCard(/.*)를 등록하면 지정되지 않는 모든 URL 요청을 처리합니다.

#include <restbed>

using namespace restbed;

void wildcard_handler(const shared_ptr<Session> session)
{
    const auto request = session->get_request();
    const auto path = request->get_path();
    const auto method = request->get_method();
    string response = "Hello from the wildcard handler!\n";
    response += "Method: " + method + "\n";
    response += "Path: " + path + "\n";
    session->close(OK, response, { { "Content-Length", to_string(response.length()) } });
}

int main(const int, const char**)
{
    auto resource = make_shared<Resource>();
    resource->set_path("/.*");  // 와일드카드로 모든 경로 처리
    resource->set_method_handler("GET", wildcard_handler);

    auto settings = make_shared<Settings>();
    settings->set_port(8080);
    Service service;
    service.publish(resource);
    service.start(settings);
    return 0;
}

 

[참고] 로깅 기능 추가

https://github.com/Corvusoft/restbed/blob/master/documentation/example/LOGGING.md

 

GitHub - Corvusoft/restbed: Corvusoft's Restbed framework brings asynchronous RESTful functionality to C++14 applications.

Corvusoft's Restbed framework brings asynchronous RESTful functionality to C++14 applications. - GitHub - Corvusoft/restbed: Corvusoft's Restbed framework brings asynchronous RESTful functi...

github.com

 

반응형

+ Recent posts