用c++方便快速的構建http server:simple_server
此組件是為了使用c++方便快速的構建http server,編寫基于http協議json格式的接口,和nginx等傳統服務器相比,更加重視開發的便捷性,項目參考restbed 實現。
特點
-
linux 2.6 +
-
單進程 + 單線程 + epoll
-
g++3.4 +
-
強調簡潔實用
依賴
-
simple_log 日志組件
-
jsoncpp json序列化組件
性能
-
qps 12000+ (短連接 ab -c 10 -n 10000 localhost:3490/hello)
-
qps 16000+ (長連接 ab -c 10 -n 10000 -k localhost:3490/hello)
構建 && 測試
make && make test && ./bin/http_server_test 3490 curl "localhost:3490/hello"
功能列表
-
http 1.0/1.1(keep-alive 支持) GET/POST請求
-
便捷的開發形式
-
Json格式的數據返回
例子
#include <sstream>#include <cstdlib>#include "simple_log.h"#include "http_server.h"void hello(Request &request, Response &response) {
Json::Value root;
root["hello"] = "world";
response.set_body(root);
}void sayhello(Request &request, Response &response) {
std::string name = request.get_param("name");
std::string age = request.get_param("age");
Json::Value root;
root["name"] = name;
root["age"] = atoi(age.c_str());
response.set_body(root);
}void login(Request &request, Response &response) {
std::string name = request.get_param("name");
std::string pwd = request.get_param("pwd"); LOG_DEBUG("login user which name:%s, pwd:%s", name.c_str(), pwd.c_str());
Json::Value root;
root["code"] = 0;
root["msg"] = "login success!";
response.set_body(root);
}int main() {
HttpServer http_server;
http_server.add_mapping("/hello", hello);
http_server.add_mapping("/sayhello", sayhello);
http_server.add_mapping("/login", login, POST_METHOD);
http_server.start(3490); return 0;
}
運行
liao@ubuntu:~/workspace/simple_server$ curl "localhost:3490/login" -d "name=tom&pwd=3"
{"code":0,"msg":"login success!"} 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!