OpenSDN source code
rest_common.cc
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2015 Juniper Networks, Inc. All rights reserved.
3  * Copyright Contributors to the OpenSDN project
4  */
5 
6 #include <rapidjson/document.h>
7 #include <rapidjson/stringbuffer.h>
8 #include <rapidjson/writer.h>
9 
10 #include <http/http_session.h>
11 #include <base/string_util.h>
12 #include "rest_common.h"
13 
14 namespace REST {
15 
16 void SendResponse(HttpSession *session,
17  const std::string &msg, int status_code, std::string context) {
18  const std::string response =
19  "HTTP/1.1 " + integerToString(status_code) + " OK\r\n"
20  "Content-Type: application/json; charset=UTF-8\r\n"
21  "Content-Length: " +
22  integerToString(msg.length()) + "\r\n" "\r\n" + msg;
23  if (context.empty()) {
24  session->Send((const uint8_t *)(response.c_str()),
25  response.length(), NULL);
26  } else {
27  session->SendSession(context, (const uint8_t *)(response.c_str()),
28  response.length(), NULL);
29  }
30 }
31 
33  const std::string &error_msg, int status_code, std::string context) {
34  contrail_rapidjson::Document document;
35  document.SetObject();
36  contrail_rapidjson::Value v;
37  document.AddMember("error",
38  v.SetString(error_msg.c_str(), document.GetAllocator()),
39  document.GetAllocator());
40  contrail_rapidjson::StringBuffer strbuf;
41  contrail_rapidjson::Writer<contrail_rapidjson::StringBuffer> writer(strbuf);
42  document.Accept(writer);
43  SendResponse(session, strbuf.GetString(), status_code, context);
44 }
45 
46 } // namespace REST
virtual bool Send(const uint8_t *data, size_t size, size_t *sent)
Definition: tcp_session.cc:430
void SendErrorResponse(HttpSession *session, const std::string &error_msg, int status_code, std::string context)
Definition: rest_common.cc:32
void SendResponse(HttpSession *session, const std::string &msg, int status_code, std::string context)
Definition: rest_common.cc:16
static const std::string integerToString(const NumberType &num)
Definition: string_util.h:20
static bool SendSession(std::string const &s, const uint8_t *data, size_t size, size_t *sent)
Definition: http_session.h:30