-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlaskCpp.cpp
More file actions
1851 lines (1633 loc) · 61 KB
/
FlaskCpp.cpp
File metadata and controls
1851 lines (1633 loc) · 61 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "FlaskCpp/FlaskCpp.h"
#include <cstdlib>
#include <csignal>
#include <thread>
#include <atomic>
#include <sys/select.h>
#include <fcntl.h>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <atomic>
const std::string LOGO = R"( _____ _ _ ____
| ___| | __ _ ___| | __ / ___|_ __ _ __
| |_ | |/ _` / __| |/ / | | | '_ \| '_ \
| _| | | (_| \__ \ < | |___| |_) | |_) |
|_| |_|\__,_|___/_|\_\ \____| .__/| .__/
|_| |_|)";
const std::string FLASK_AUTHORS = R"(LSH9832 & Andrew-Gomonov)";
const std::string FLASK_COMPILE_TIME = __DATE__ + std::string(" ") + __TIME__;
std::atomic<bool> flask_first = true;
std::atomic<bool> verbose_default = true;
void flaskSetDefaultVerbose(bool flag)
{
verbose_default = flag;
}
std::string parse_cookies(std::pair<std::string, std::string> pair, size_t seconds)
{
std::ostringstream oss;
oss << " " << pair.first << "=" << pair.second << ";";
oss << " max-age=" << seconds << ";";
oss << " HttpOnly;";
// std::cout << oss.str() << std::endl;
return oss.str();
}
static inline std::string url_decode(const std::string& encoded_str) {
std::string decoded_str;
for (size_t i = 0; i < encoded_str.size(); ++i) {
if (encoded_str[i] == '%') {
if (i + 2 < encoded_str.size()) {
std::string hex = encoded_str.substr(i + 1, 2);
char decoded_char = static_cast<char>(std::stoi(hex, nullptr, 16));
decoded_str += decoded_char;
i += 2;
}
} else {
decoded_str += encoded_str[i];
}
}
return decoded_str;
}
static inline bool stringStartsWith(std::string str_, const std::string prefix)
{
size_t str_len = str_.length();
size_t prefix_len = prefix.length();
if (prefix_len > str_len) return false;
return str_.find(prefix) == 0;
}
static inline bool stringEndsWith(std::string str_, const std::string suffix)
{
size_t str_len = str_.length();
size_t suffix_len = suffix.length();
if (suffix_len > str_len) return false;
return (str_.find(suffix, str_len - suffix_len) == (str_len - suffix_len));
}
std::string strfnowtime(std::string format="%Y-%m-%d %H:%M:%S")
{
std::ostringstream oss;
auto now = std::chrono::system_clock::now();
std::time_t current_time = std::chrono::system_clock::to_time_t(now);
std::tm* local_time = std::localtime(¤t_time);
oss << std::put_time(local_time, format.c_str());
return oss.str();
}
std::vector<char> readFileBytesData(const std::string& file_path, bool verbose) {
std::vector<char> file_data;
// 以二进制模式打开文件
std::ifstream file(file_path, std::ios::binary | std::ios::ate);
if (!file.is_open()) {
std::cerr << "错误:无法打开文件 " << file_path << std::endl;
return file_data;
}
// 获取文件大小
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
// 检查文件大小是否合理
if (size <= 0) {
std::cerr << "错误:文件大小无效或文件为空" << std::endl;
return file_data;
}
// 预留空间以提高性能
file_data.resize(size);
// 读取整个文件到vector
if (!file.read(file_data.data(), size)) {
std::cerr << "错误:读取文件失败" << std::endl;
file_data.clear();
return file_data;
}
if(verbose) std::cout << "成功读取文件,大小: " << size << " 字节" << std::endl;
return file_data;
}
// 构造函数
FlaskCpp::FlaskCpp(std::string server_name, size_t minThreads, size_t maxThreads)
:running(false), threadPool(minThreads, maxThreads), server_name(server_name)
{
verbose = verbose_default;
if (flask_first && verbose)
{
flask_first = false;
std::cout << "\033[33m\033[1m" << LOGO << "\033[0m" << std::endl;
std::cout << "FlaskCpp Compile Time: \033[35m\033[1m"
<< FLASK_COMPILE_TIME << "\033[0m" << std::endl;
std::cout << "FlaskCpp Authors:\033[36m\033[1m " << FLASK_AUTHORS << "\033[0m" << std::endl;
}
}
// 构造函数
FlaskCpp::FlaskCpp(int port, bool verbose, bool enableHotReload, size_t minThreads, size_t maxThreads)
: port(port), verbose(verbose), enableHotReload(enableHotReload), running(false), threadPool(minThreads, maxThreads) {
if (verbose) {
if (flask_first)
{
flask_first = false;
std::cout << LOGO << std::endl;
std::cout << "FlaskCpp Compile Time: \033[35m\033[1m"
<< FLASK_COMPILE_TIME << "\033[0m" << std::endl;
std::cout << "FlaskCpp Authors:\033[36m\033[1m " << FLASK_AUTHORS << "\033[0m" << std::endl;
}
}
}
void FlaskCpp::setSecretKey(const std::string& key)
{
serialzer.setKey(key);
}
void FlaskCpp::setLog(loggerWrite w)
{
logger = w;
}
void FlaskCpp::setTemplate(const std::string& name, const std::string& content) {
templateEngine.setTemplate(name, content);
}
void FlaskCpp::setConfigUpdateListener(const std::string& file_path, TemplateEngine::FileChangedCallback callback)
{
templateEngine.addConfigUpdateListener(file_path, callback);
}
void FlaskCpp::log(const flaskcpp::LogMsg& msg)
{
if (logger)
{
logger(msg);
}
else if (verbose) {
std::cout << "[\033[32m" << strfnowtime() << "\033[0m] "
<< msg.content << std::endl;
}
}
void FlaskCpp::setTemplateChangedCallback(TemplateEngine::FileChangedCallback callback)
{
template_changed_callback = [callback](const std::string& path)
{
callback(path);
};
}
void FlaskCpp::route2(const std::string& path, UniteHandler handler)
{
if (path.find("<") != path.npos && path.find(">") != path.npos)
{
paramROUTES.push_back({path, handler});
if (logger)
{
std::ostringstream oss;
oss << "Param route added: " << path;
logger({2, oss.str(), __LINE__, __FILE__, __func__});
}
else if (verbose) {
std::cout << "[\033[32m" << strfnowtime() << "\033[0m] "
<< "\033[32m\033[1mParam route added\033[0m: "
<< path << std::endl;
}
}
else
{
ROUTES[path] = [handler](const RequestData& req) {
return handler(req);
};
if (logger)
{
std::ostringstream oss;
oss << "Route added: " << path;
logger({2, oss.str(), __LINE__, __FILE__, __func__});
}
else if (verbose) {
std::cout << "[\033[32m" << strfnowtime() << "\033[0m] \033[32m\033[1m" << "Route added\033[0m: " << path << std::endl;
}
}
}
void FlaskCpp::route(const std::string& path, SimpleHandler handler) [[deprecated]]
{
routes[path] = [handler](const RequestData& req) {
return handler(req);
};
if (logger)
{
std::ostringstream oss;
oss << "Route added: " << path;
logger({2, oss.str(), __LINE__, __FILE__, __func__});
}
else if (verbose) {
std::cout << "[\033[32m" << strfnowtime() << "\033[0m] \033[32m\033[1m" << "Route added\033[0m: " << path << std::endl;
}
}
void FlaskCpp::routeFile(const std::string& path, FlaskFileHandler handler) [[deprecated]]
{
file_routes[path] = [handler](const RequestData& req) {
return handler(req);
};
if (logger)
{
std::ostringstream oss;
oss << "File Route added: " << path;
logger({2, oss.str(), __LINE__, __FILE__, __func__});
}
else if (verbose) {
std::cout << "[\033[32m" << strfnowtime() << "\033[0m] \033[32m\033[1m" << "File Route added\033[0m: " << path << std::endl;
}
}
std::vector<std::string> FlaskCpp::getAllTemplateNames()
{
return templateEngine.getAllTemplateNames();
}
void FlaskCpp::routeParam(const std::string& pattern, ComplexHandler handler) [[deprecated]]
{
paramRoutes.push_back({pattern, handler});
if (logger)
{
std::ostringstream oss;
oss << "Param route added: " << pattern;
logger({2, oss.str(), __LINE__, __FILE__, __func__});
}
else if (verbose) {
std::cout << "[\033[32m" << strfnowtime() << "\033[0m] " << "\033[32m\033[1mParam route added\033[0m: " << pattern << std::endl;
}
}
std::pair<std::string, std::string> FlaskCpp::generateSession(std::map<std::string, std::string> session, int max_age)
{
std::string map_str = serialzer.map2str(session);
// std::cout << map_str << std::endl;
std::string dump_str = serialzer.dumps(map_str);
// std::cout << dump_str << std::endl;
std::string load_str = serialzer.loads(dump_str);
// std::cout << load_str << std::endl;
std::map<std::string, std::string> map;
serialzer.str2map(load_str, map);
// for (auto& it: map)
// {
// std::cout << it.first << ": " << it.second << std::endl;
// }
return {"Set-Cookie", parse_cookies({"session", dump_str}, max_age)};
}
void FlaskCpp::loadTemplatesFromDirectory(const std::string& directoryPath)
{
namespace fs = std::filesystem;
templatesDirectory = directoryPath;
if (!fs::exists(directoryPath) || !fs::is_directory(directoryPath)) {
if (logger)
{
std::ostringstream oss;
oss << "Templates directory does not exist: " << directoryPath;
logger({3, oss.str(), __LINE__, __FILE__, __func__});
}
else
std::cerr << "[\033[32m" << strfnowtime() << "\033[0m] " << "\033[31m\033[1mTemplates directory does not exist\033[0m: " << directoryPath << std::endl;
return;
}
for (const auto& entry : fs::directory_iterator(directoryPath)) {
if (entry.is_regular_file() && entry.path().extension() == ".html") {
std::ifstream file(entry.path());
if (file) {
std::ostringstream ss;
ss << file.rdbuf();
std::string content = ss.str();
std::string filename = entry.path().filename().string();
setTemplate(filename, content);
// 保存文件的时间戳
templatesTimestamps[entry.path().string()] = fs::last_write_time(entry);
if (logger)
{
std::ostringstream oss;
oss << "Loaded template: " << filename;
logger({2, oss.str(), __LINE__, __FILE__, __func__});
}
else if (verbose) {
std::cout << "[\033[32m" << strfnowtime() << "\033[0m] " << "\033[32m\033[1mLoaded template\033[0m: "
<< filename << std::endl;
}
} else {
if (logger)
{
std::ostringstream oss;
oss << "Failed to open template file: " << entry.path();
logger({3, oss.str(), __LINE__, __FILE__, __func__});
}
else
std::cerr << "[\033[32m" << strfnowtime() << "\033[0m] " << "\033[31m\033[1mFailed to open template file\033[0m: " << entry.path() << std::endl;
}
}
}
}
void FlaskCpp::setCheckTaskDuration(size_t ms)
{
check_duration = ms?ms:1;
}
void FlaskCpp::addCheckTask(TemplateEngine::CheckTask task)
{
templateEngine.addCheckTask(task);
}
void FlaskCpp::monitorTemplates() {
namespace fs = std::filesystem;
while (running.load()) {
std::this_thread::sleep_for(std::chrono::milliseconds(check_duration)); // 适中的检查间隔
templateEngine.checkConfigOnce();
templateEngine.execAllCheckTask();
if (templatesDirectory.empty()) continue;
for (const auto& entry : fs::directory_iterator(templatesDirectory)) {
if (entry.is_regular_file() && entry.path().extension() == ".html") {
std::string filePath = entry.path().string();
auto currentTimestamp = fs::last_write_time(entry);
// 如果文件已更改则重新启动
if (templatesTimestamps.find(filePath) != templatesTimestamps.end()) {
if (templatesTimestamps[filePath] != currentTimestamp) {
std::ifstream file(entry.path());
if (file) {
std::ostringstream ss;
ss << file.rdbuf();
std::string content = ss.str();
std::string filename = entry.path().filename().string();
setTemplate(filename, content);
templatesTimestamps[filePath] = currentTimestamp;
if (template_changed_callback)
{
template_changed_callback(filename);
}
if (logger)
{
std::ostringstream oss;
oss << "Template reloaded: " << filename;
logger({1, oss.str(), __LINE__, __FILE__, __func__});
}
else if (verbose) {
std::cout << "[\033[32m" << strfnowtime() << "\033[0m] \033[33mTemplate reloaded: "
<< filename << "\033[0m" << std::endl;
}
}
}
} else {
// 更新文件时间
templatesTimestamps[filePath] = currentTimestamp;
}
}
}
}
}
void FlaskCpp::runAsync() {
if (running.load()) {
if (logger)
{
std::ostringstream oss;
oss << "Server is already running.";
logger({1, oss.str(), __LINE__, __FILE__, __func__});
}
else
std::cerr << "[\033[32m" << strfnowtime() << "\033[0m] " << "Server is already running." << std::endl;
return;
}
running.store(true);
// 仅在启用热重新加载时运行监视流
if (enableHotReload) {
hotReloadThread = std::thread(&FlaskCpp::monitorTemplates, this);
if (logger)
{
std::ostringstream oss;
oss << "Hot reload is enabled. Monitoring templates for changes.";
logger({2, oss.str(), __LINE__, __FILE__, __func__});
}
else if (verbose) {
std::cout << "[\033[32m" << strfnowtime() << "\033[0m] "
<< "\033[33mHot reload is enabled. Monitoring templates for changes.\033[0m" << std::endl;
}
} else {
if (verbose) {
if (logger)
{
std::ostringstream oss;
oss << "Hot reload is disabled.";
logger({1, oss.str(), __LINE__, __FILE__, __func__});
}
else
std::cout << "[\033[32m" << strfnowtime() << "\033[0m] " << "\033[33mHot reload is disabled.\033[0m" << std::endl;
}
}
// 将服务器启动任务添加到高优先级线程池
// 假设0是最高优先级
threadPool.enqueue(0, [this](){
this->run();
});
}
void FlaskCpp::run() {
int serverSocket = socket(AF_INET6, SOCK_STREAM, 0);
if (serverSocket == -1) {
if (logger)
{
std::ostringstream oss;
oss << "Failed to create socket.";
logger({4, oss.str(), __LINE__, __FILE__, __func__});
}
else
std::cerr << "[\033[32m" << strfnowtime() << "\033[0m] " << "Failed to create socket." << std::endl;
running.store(false);
return;
}
int opt = 0;
setsockopt(serverSocket, IPPROTO_IPV6, IPV6_V6ONLY, &opt, sizeof(opt));
opt = 1;
setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
sockaddr_in6 serverAddr = {};
serverAddr.sin6_family = AF_INET6;
serverAddr.sin6_addr = in6addr_any;
serverAddr.sin6_port = htons(port);
bind_success = true;
if (bind(serverSocket, (sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) {
if (logger)
{
std::ostringstream oss;
oss << "Bind failed.";
logger({4, oss.str(), __LINE__, __FILE__, __func__});
}
else
std::cerr << "[\033[32m" << strfnowtime() << "\033[0m] " << "Bind failed." << std::endl;
close(serverSocket);
bind_success = false;
// running.store(false);
// stop();
return;
}
if (listen(serverSocket, 100) == -1) { // 增加Backlog以获得更大的负载
if (logger)
{
std::ostringstream oss;
oss << "Listen failed.";
logger({4, oss.str(), __LINE__, __FILE__, __func__});
}
else
std::cerr << "[\033[32m" << strfnowtime() << "\033[0m] " << "Listen failed." << std::endl;
close(serverSocket);
bind_success = false;
// running.store(false);
// stop();
return;
}
if (logger)
{
std::ostringstream oss;
oss << "ThreadPool initialized with range [" << threadPool.getMinThreads() << ", " << threadPool.getMaxThreads() << "]";
logger({1, oss.str(), __LINE__, __FILE__, __func__});
}
else if (verbose)
{
std::cout << "[\033[32m" << strfnowtime() << "\033[0m] " << "\033[32m\033[1mThreadPool initialized with range ["
<< threadPool.getMinThreads()
<< ", " << threadPool.getMaxThreads() << "]\033[0m" << std::endl;
}
if (logger)
{
std::ostringstream oss;
oss << "Server is running on http://0.0.0.0:" << port;
logger({1, oss.str(), __LINE__, __FILE__, __func__});
}
else if (verbose) {
std::cout << "[\033[32m" << strfnowtime() << "\033[0m] " << "Server is running on \033[32mhttp://0.0.0.0:" << port << "\033[0m" << std::endl;
}
while (running.load()) { // 支持服务器停止的循环
sockaddr_in6 clientAddr;
socklen_t clientLen = sizeof(clientAddr);
int clientSocket = accept(serverSocket, (sockaddr*)&clientAddr, &clientLen);
if (clientSocket == -1) {
if (running.load()) { // 检查服务器是否已停止
if (logger)
{
std::ostringstream oss;
oss << "Failed to accept connection.";
logger({4, oss.str(), __LINE__, __FILE__, __func__});
}
else
std::cerr << "[\033[32m" << strfnowtime() << "\033[0m] " << "Failed to accept connection." << std::endl;
}
continue;
}
// 设置读取第一个数据块的超时(5秒)
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
setsockopt(clientSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout));
// 读取查询方法的前4096字节
char buffer[4096];
ssize_t bytesRead = recv(clientSocket, buffer, sizeof(buffer), MSG_PEEK);
std::string requestSample;
if (bytesRead > 0) {
requestSample = std::string(buffer, bytesRead);
}
// 从第一行提取查询方法
std::string method = "GET"; // 默认GET
size_t firstLineEnd = requestSample.find("\r\n");
if (firstLineEnd != std::string::npos) {
std::string firstLine = requestSample.substr(0, firstLineEnd);
std::istringstream iss(firstLine);
iss >> method;
}
// 根据查询方法设置优先级
int priority = 5; // 默认平均优先级
if (method == "GET") {
priority = 1; // Get高优先级
} else if (method == "POST") {
priority = 2; // Post平均优先级
} else if (method == "PUT" || method == "DELETE") {
priority = 3; // 低优先级的put和delete
} else {
priority = 4; // 其他方法的优先级非常低
}
// if (verbose) {
// std::cout << "Request Method: " << method << " - Assigned Priority: " << priority << std::endl;
// }
char clientIP[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &clientAddr.sin6_addr, clientIP, INET6_ADDRSTRLEN);
bool fromIPV4 = stringStartsWith(clientIP, "::ffff:");
// 将客户端处理添加到具有特定优先级的线程池
threadPool.enqueue(priority, [this, clientSocket, clientIP, fromIPV4]() {
this->handleClient(clientSocket, std::string(fromIPV4?clientIP+7:clientIP));
});
}
close(serverSocket);
}
void FlaskCpp::run(int port, bool verbose, bool enableHotReload)
{
this->port = port;
this->verbose= verbose;
this->enableHotReload = enableHotReload;
this->run();
}
void FlaskCpp::runAsync(int port, bool verbose, bool enableHotReload)
{
this->port = port;
this->verbose= verbose;
this->enableHotReload = enableHotReload;
this->runAsync();
}
bool FlaskCpp::isRunning()
{
return running && bind_success;
}
void FlaskCpp::stop() {
if (!running.load() && bind_success) return;
if (logger)
{
std::ostringstream oss;
oss << "please wait for http server stop.";
logger({1, oss.str(), __LINE__, __FILE__, __func__});
}
else if (verbose) std::cout << "[\033[32m" << strfnowtime() << "\033[0m] " << "(\033[36m" << server_name << "\033[0m) "
<< "please wait for http server stop" << std::endl;
// std::cout << __LINE__ << std::endl;
running.store(false);
// std::cout << __LINE__ << std::endl;
// 创建与服务器套接字的连接以终止Accept锁
int dummySocket = socket(AF_INET, SOCK_STREAM, 0);
if(dummySocket != -1){
sockaddr_in serverAddr = {};
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
serverAddr.sin_port = htons(port);
connect(dummySocket, (sockaddr*)&serverAddr, sizeof(serverAddr));
close(dummySocket);
}
// std::cout << __LINE__ << std::endl;
// 停止线程池
threadPool.shutdown();
// std::cout << __LINE__ << std::endl;
// 等待监控线程完成
if (enableHotReload && hotReloadThread.joinable()) {
hotReloadThread.join();
}
// std::cout << __LINE__ << std::endl;
if (logger)
{
std::ostringstream oss;
oss << "Server has been stopped.";
logger({2, oss.str(), __LINE__, __FILE__, __func__});
}
else if (verbose) {
std::cout << "[\033[32m" << strfnowtime() << "\033[0m] " << "Server has been stopped." << std::endl;
}
}
std::string FlaskCpp::renderTemplate(const std::string& templateName, const TemplateEngine::Context& context) {
return templateEngine.render(templateName, context);
}
std::string FlaskCpp::jump_to(const std::string& route_, const std::string& msg, size_t delay)
{
std::string html_string = R"(<!DOCTYPE html>
<html>
<head>
<title>redirect</title>
<meta http-equiv="refresh" content=")" + std::to_string(delay) + ";url=" + route_ + R"(">
</head>
<body>
<p>)" + msg + R"(</p>
wait for )" + std::to_string(delay) + R"(seconds.
</body>
</html>)";
return html_string;
}
std::string FlaskCpp::buildResponse(const std::string& status_code,
const std::string& content_type,
const std::string& body,
const std::vector<std::pair<std::string, std::string>>& extra_headers) {
std::ostringstream response;
response << "HTTP/1.1 " << status_code << "\r\n";
response << "Content-Type: " << content_type;
// 为文本内容类型添加charset=utf-8
if (content_type.find("text/") != std::string::npos || content_type.find("application/json") != std::string::npos) {
response << "; charset=utf-8";
}
response << "\r\n";
response << "Content-Length: " << body.size() << "\r\n";
// 添加其他标题,包括多个设置cookie
for (const auto& header : extra_headers) {
if (header.first.empty()) continue;
response << header.first << ": " << header.second << "\r\n";
}
response << "Connection: close\r\n\r\n";
response << body;
return response.str();
}
template <typename T>
std::string FlaskCpp::buildResponse(const std::string& status_code,
int file_type, std::vector<T> file_data,
const std::vector<std::pair<std::string, std::string>>& extra_headers)
{
std::ostringstream response;
response << "HTTP/1.1 " << status_code << "\r\n";
if (file_type >=0 && file_type < __flaskFileTypeMap__.size())
{
response << "Content-Type: " << __flaskFileTypeMap__[file_type] << "\r\n";
}
else
{
response << "Content-Type: application/octet-stream\r\n";
}
response << "Content-Length: " << file_data.size() << "\r\n";
bool has_cache_control = false;
for (const auto& header : extra_headers) {
if (header.first.empty()) continue;
if (header.first == "Cache-Control") has_cache_control = true;
response << header.first << ": " << header.second << "\r\n";
}
if (!has_cache_control)
{
response << "Cache-Control: public, max-age=3600\r\n";
}
response << "Connection: close\r\n\r\n";
// 将二进制数据写入响应体
response.write((char*)file_data.data(), file_data.size() * sizeof(T));
return response.str();
}
template std::string FlaskCpp::buildResponse<char>(
const std::string&, int, std::vector<char>,
const std::vector<std::pair<std::string, std::string>>&);
template std::string FlaskCpp::buildResponse<int8_t>(
const std::string&, int, std::vector<int8_t>,
const std::vector<std::pair<std::string, std::string>>&);
template std::string FlaskCpp::buildResponse<uint8_t>(
const std::string&, int, std::vector<uint8_t>,
const std::vector<std::pair<std::string, std::string>>&);
template <typename T>
std::string FlaskCpp::send_file(std::vector<T> file_data, std::string file_name, bool as_attachment,
const std::vector<std::pair<std::string, std::string>>& extra_headers)
{
std::ostringstream response;
response << "HTTP/1.1 200 OK\r\n";
if (file_data.size())
{
response << "Content-Type: " << getFileTypeString(-2, file_name) << "\r\n";
}
else
{
return generate404Error();
}
response << "Content-Length: " << file_data.size() << "\r\n";
auto fileExtraHeader = genFileExtraSettings(file_name, as_attachment);
response << fileExtraHeader.first << ": " << fileExtraHeader.second;
bool has_cache_control = false;
for (const auto& header : extra_headers) {
if (header.first.empty()) continue;
if (header.first == "Cache-Control") has_cache_control = true;
response << header.first << ": " << header.second << "\r\n";
}
if(!has_cache_control)
{
response << "Cache-Control: public, max-age=3600\r\n";
}
response << "Connection: close\r\n\r\n";
// 将二进制数据写入响应体
response.write((char*)file_data.data(), file_data.size() * sizeof(T));
return response.str();
}
template std::string FlaskCpp::send_file<char>(std::vector<char>, std::string, bool,
const std::vector<std::pair<std::string, std::string>>&);
template std::string FlaskCpp::send_file<int8_t>(std::vector<int8_t>, std::string, bool,
const std::vector<std::pair<std::string, std::string>>&);
template std::string FlaskCpp::send_file<uint8_t>(std::vector<uint8_t>, std::string, bool,
const std::vector<std::pair<std::string, std::string>>&);
std::string FlaskCpp::send_file(std::string file_path, std::string file_name, bool as_attachment,
const std::vector<std::pair<std::string, std::string>>& extra_headers)
{
auto data = readFileBytesData(file_path);
if (data.size())
{
if (!file_name.size())
{
int k = -1;
for (int i=0;i<file_path.size();i++)
{
if (file_path[i] == '/')
{
k = i;
}
}
file_name = file_path.substr(k+1);
}
return this->send_file(data, file_name, as_attachment, extra_headers);
}
else
{
return generate404Error();
}
}
std::string FlaskCpp::buildResponse(const std::string& status_code,
int file_type, std::string file_path,
const std::vector<std::pair<std::string, std::string>>& extra_headers)
{
auto data = readFileBytesData(file_path);
if (data.size())
{
return this->buildResponse(status_code, file_type, data, extra_headers);
}
else
{
return generate404Error();
}
}
std::string FlaskCpp::setCookie(const std::string& name, const std::string& value,
const std::string& path, const std::string& expires,
bool httpOnly, bool secure, const std::string& sameSite) {
std::ostringstream cookie;
cookie << name << "=" << value;
cookie << "; Path=" << path;
if (!expires.empty()) {
cookie << "; Expires=" << expires;
}
if (httpOnly) {
cookie << "; HttpOnly";
}
if (secure) {
cookie << "; Secure";
}
if (!sameSite.empty()) {
cookie << "; SameSite=" << sameSite;
}
return cookie.str();
}
std::string FlaskCpp::deleteCookie(const std::string& name,
const std::string& path) {
std::ostringstream cookie;
cookie << name << "=deleted";
cookie << "; Path=" << path;
cookie << "; Expires=Thu, 01 Jan 1970 00:00:00 GMT";
cookie << "; HttpOnly";
return cookie.str();
}
void FlaskCpp::handleClient(int clientSocket, const std::string& clientIP) {
int status = 200;
std::string method="Unknown", path="Unknown";
try {
// std::cout << 1 << std::endl;
std::string requestStr = readRequest(clientSocket);
// std::cout << 2 << std::endl;
RequestData reqData;
parseRequest(requestStr, reqData);
reqData.path = url_decode(reqData.path);
// std::cout << 3 << ". " << reqData.method << "," << reqData.path << std::endl;
if (reqData.path[0] == '/')
{
method = reqData.method;
path = reqData.full_path;
}
else
{
return;
}
std::string response;
bool is_file=false;
flaskcpp::FileHandler fh;
flaskcpp::Response resp;
{
std::lock_guard<std::mutex> lock(routeMutex);
UniteHandler unite_handler = nullptr;
ComplexHandler handler = nullptr;
// 试图找到准确的路线。
auto uit = ROUTES.find(reqData.path);
if (uit != ROUTES.end())
{
unite_handler = uit->second;
}
else
{
for (auto &pr : paramROUTES) {
if (matchParamRoute(reqData.path, pr.pattern, reqData.routeParams)) {
unite_handler = pr.handler;
break;
}
}
}
if (unite_handler)
{
resp = unite_handler(reqData);
if (!resp.type)
{
sendResponse(clientSocket, generate404Error("404 NOT FOUND"));
status = 404;
}
}
// 如果新接口没有匹配,尝试匹配老接口,不建议使用
else
{
auto it = routes.find(reqData.path);
if (it != routes.end()) {
handler = it->second;
} else {
// 检查带有参数的路由
for (auto &pr : paramRoutes) {
if (matchParamRoute(reqData.path, pr.pattern, reqData.routeParams)) {
handler = pr.handler;
break;
}
}
}
if (!handler) {
// 寻找是否是本地文件
FlaskFileHandler fhandler = nullptr;
auto it = file_routes.find(reqData.path);
if (it != file_routes.end()) {
fhandler = it->second;
is_file = true;
fhandler(reqData).copyTo(fh);
}
// 检查静态文件
else if (!serveStaticFile(reqData, response)) {
response = generate404Error();