add json Response

This commit is contained in:
an-tao 2018-05-21 18:54:00 +08:00
parent ee1ff8950c
commit 652560697d
5 changed files with 50 additions and 1 deletions

View File

@ -1,3 +1,3 @@
link_libraries(drogon trantor uuid pthread)
link_libraries(drogon trantor uuid pthread jsoncpp)
AUX_SOURCE_DIRECTORY(static_link_example DIR_STATIC)
add_executable(webapp ${DIR_STATIC})

View File

@ -0,0 +1,19 @@
#include "JsonTestController.h"
#include <json/json.h>
void JsonTestController::asyncHandleHttpRequest(const HttpRequest& req,std::function<void (HttpResponse &)>callback)
{
Json::Value json;
json["path"]="json";
json["name"]="json test";
Json::Value array;
for(int i=0;i<5;i++)
{
Json::Value user;
user["id"]=i;
user["name"]="none";
array.append(user);
}
json["rows"]=array;
auto resp=std::unique_ptr<HttpResponse>(HttpResponse::newHttpResponse(json));
callback(*resp);
}

View File

@ -0,0 +1,15 @@
#pragma once
#include <drogon/HttpSimpleController.h>
using namespace drogon;
class JsonTestController:public drogon::HttpSimpleController<JsonTestController>
{
public:
//TestController(){}
virtual void asyncHandleHttpRequest(const HttpRequest& req,std::function<void (HttpResponse &)>callback)override;
PATH_LIST_BEGIN
PATH_ADD("/json");
PATH_LIST_END
};

View File

@ -21,6 +21,8 @@
#pragma once
#include <string>
#include <json/json.h>
using std::string;
#define CT_APPLICATION_JSON 1
#define CT_TEXT_PLAIN 2
@ -98,6 +100,7 @@ namespace drogon
virtual std::string getBody() const=0;
static HttpResponse* newHttpResponse();
static HttpResponse* newHttpResponse(const Json::Value &data);
};

View File

@ -26,6 +26,18 @@ HttpResponse* HttpResponse::newHttpResponse()
{
return new HttpResponseImpl;
}
HttpResponse* HttpResponse::newHttpResponse(const Json::Value &data)
{
auto res=new HttpResponseImpl;
res->setStatusCode(HttpResponse::k200Ok);
res->setContentTypeCode(CT_APPLICATION_JSON);
Json::StreamWriterBuilder builder;
builder["commentStyle"] = "None";
builder["indentation"] = "";
res->setBody(writeString(builder, data));
return res;
}
const std::string HttpResponseImpl::web_content_type_to_string(uint8_t contenttype)
{
switch(contenttype) {