RESTful API的Hellow,World!

什么,你连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!总是让人开心的,希望你也能顺利完成。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值