什麼,你連RESTful API都不知道!
開個玩笑。因爲疫情的原因呆在家裏,準備回學校了。過程中公司的導師聯繫我做一個小項目,需要使用到RESTful API的接口。這種接口已經是後臺架構設計的一種趨勢了,還是有必要了解一下的。但是因爲我在學校的專業和這個完全不相關,所以摸索了很久才最終搞了個Hellow,World!不過就算這樣也還是很激動了,所以打算記錄一下,因爲我也是完全新手,所以儘量寫的詳細一點。
好了,回到正題。首先說明一下,我導師要求我使用C++開發。首先給出一個小的調研:
所以我最開始是打算使用pistache的,但是無奈,我在阿里雲申請的服務器(什麼,你竟然不知道新用戶可以免費用一個月?!)太拉閘,想升級個GCC都升級不了,腦殼疼:
最後問了一下我的導師,發現公司的架構還是在C++11的基礎上開發的,所以我還是選擇了restbed。
首先感謝這篇文章的分享:here。不過因爲該博主的一些細節並沒有給出,所以我這裏來完善一下。
安裝restbed
這一步的話大家按照上面那片文章就可以搞定了,這裏不再贅述。
編寫源文件
因爲我的開發環境是再ECS(彈性雲服務器)上,所以不能像IDE一樣自動編譯了。這裏一共有三個源文件需要編寫。
1 restbed.cpp
#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( "./" + filename, ifstream::in );
if ( stream.is_open( ) )
{
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( const int, const char** )
{
auto resource = make_shared< Resource >( );
resource->set_path( "/static/{filename: [a-z]*\\.html}" );
resource->set_method_handler( "GET", get_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;
}
2 index.html
Hellow,World!
可以看到,這個就是我們需要得到的內容。
3 Makefile
restbed: restbed.cpp
g++ restbed.cpp -o restbed -I /usr/local/restbed/distribution/include -L /usr/local/restbed/distribution/library -lrestbed
clean:
rm restbed.o restbed
這裏一個比較關鍵的點就是我把restbed安裝好以後的頭文件和庫cp到了/usr/local/restbed下,這個大家應該根據實際情況進行修改。
注意,這三個文件應該放在同一個文件夾下面。
編譯運行
準備好原文件後就可以編譯了,當然是在放Makefile的目錄下執行:
make
然後執行程序,注意還是在當前目錄:
./restbed
因爲我是使用的ECS,所以就重新開了一個連接,然後執行:
curl http://localhost:1984/static/index.html
好啦,如果返回了Hellow,World!就說明成功啦!
結語
其實回過頭來看,整個過程還是非常簡單的,但是因爲中間涉及的知識比較多(主要是Makefile的編寫),所以還是花了不少時間,不過看到Hellow,World!總是讓人開心的,希望你也能順利完成。