-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_callback.cpp
101 lines (84 loc) · 2.79 KB
/
client_callback.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//
// Created by heshamovic on 11/16/18.
//
#include "client_callback.h"
#include <vector>
#include <sstream>
#include <iostream>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <string>
#include "http/response.h"
void GET_callback(const std::vector<std::string> &results, client::net::socketstream &ss);
void POST_callback(const std::vector<std::string> &results, client::net::socketstream &ss);
std::string read_response(client::net::socketstream &ss);
std::map<std::string, cfunc> callbackMap;
void callback::init() {
callbackMap["GET"] = GET_callback;
callbackMap["POST"] = POST_callback;
}
void GET_callback(const std::vector<std::string> &results, client::net::socketstream &ss) {
std::ostringstream oss;
std::istringstream iss, riss;
std::string response_status, http_version, status_msg, data;
int status;
std::string response = read_response(ss);
iss.str(response);
std::getline(iss, response_status);
riss.str(response_status);
riss >> http_version >> status;
status_msg = riss.str().substr(riss.tellg());
if (status == http_response::status::OK){
// // Skip headers
while(std::getline(iss, data) && data.compare("\r"));
data = iss.str().substr(iss.tellg());
std::ofstream out(results[1]);
std::cout << data << std::endl;
out << data;
out.close();
}
else {
std::cerr << status << " " << status_msg << std::endl;
}
std::cout << response << std::endl;
}
void POST_callback(const std::vector<std::string> &results, client::net::socketstream &ss) {
std::ostringstream oss;
std::istringstream iss, riss;
std::string response_status, http_version, status_msg, data;
int status;
std::string response = read_response(ss);
iss.str(response);
std::getline(iss, response_status);
riss.str(response_status);
riss >> http_version >> status;
status_msg = riss.str().substr(riss.tellg());
if (status == client::ok_status) {
std::cout << status << " " << status_msg << std::endl;
} else {
std::cerr << status << " " << status_msg << std::endl;
}
std::cout << response << std::endl;
}
std::string read_response(client::net::socketstream &ss){
char c;
std::ostringstream oss;
int len;
std::string line;
// Read till content length
while(std::getline(ss, line)){
oss << line << "\n";
if(!line.find("Content-Length")){
std::vector<std::string> results;
boost::split(results, line, [](char c) { return c == ' '; });
len = std::stoi(results.back());
}
else if(!line.find("\r"))
break;
}
for(int i = 0; i<len; i++){
ss.get(c);
oss.put(c);
}
return oss.str();
}