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