-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathConfigure.cpp
executable file
·104 lines (83 loc) · 2.42 KB
/
Configure.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
102
103
104
#include "Configure.h"
Configure *Configure::cfg = NULL;
static void repaceTab(string &str) {
for (unsigned int i=0; i<str.length(); i++) {
if (str[i] == '\t'|| str[i] == '\b' || str[i] == '\v' || str[i] == '\r') {
str[i] = ' ';
}
}
}
static string& trim(string& str)
{
str.erase(str.find_last_not_of(' ')+1, string::npos);
str.erase(0, str.find_first_not_of(' '));
return str;
}
void Configure::initMember(Configure *cfg) {
cfg->url = cfg->info["server_url"];
cfg->heartbeat = cfg->info["msg_heart_beat"];
cfg->notify = cfg->info["msg_notify"];
cfg->statis_port = cfg->ToShort(cfg->info["statis_port"]);
cfg->heartbeat_port = cfg->ToShort(cfg->info["heartbeat_port"]);
cfg->timeout = cfg->ToInt(cfg->info["timeout"]);
cfg->sleep_mill = cfg->ToInt(cfg->info["sleep_mill"]);
cfg->req_per_second = cfg->ToInt(cfg->info[REQUESTS_PER_SECOND_NAME]);
cfg->max_connections = cfg->ToInt(cfg->info[MAX_CONNECTIONS_NAME]);
}
void Configure::readCommonConfig(Configure *cfg, string &line) {
string::size_type index = line.find_first_of(" ", 0);
string key = line.substr(0, index);
string value = line.substr(index+1);
cfg->info[trim(key)] = trim(value);
}
void Configure::readHttpHeader(Configure *cfg, string &line) {
string::size_type index = line.find_first_of(" ", 0);
string key = line.substr(0, index);
string value = line.substr(index+1);
cfg->http_header.push_back(trim(key));
cfg->http_header.push_back(trim(value));
}
bool Configure::changeFlag(string &line) {
if (line.find("[http_header]") != line.npos) {
return true;
}
return false;
}
Configure *Configure::readConfigFile(const char *filePath) {
if (cfg != NULL) {
return cfg;
}
cfg = new Configure();
ifstream ios(filePath, ios::in);
if (!ios.good()) {
cout << "open configure file failed." << endl;
initMember(cfg);
return cfg;
}
int flag = 0;
while (!ios.eof()) {
string line;
getline(ios, line);
repaceTab(line);
if (flag == 0) {
flag = changeFlag(line) ? 1 : 0;
if (flag) {
continue;
}
readCommonConfig(cfg, line);
} else {
readHttpHeader(cfg, line);
}
}
initMember(cfg);
return cfg;
}
string& Configure::getValue(const char *key) {
return info[key];
}
int Configure::ToInt(string &val) {
return atoi(val.c_str());
}
unsigned short Configure::ToShort(string &val) {
return (unsigned short)ToInt(val);
}