-
Notifications
You must be signed in to change notification settings - Fork 376
/
Copy pathtest_coro_http_server.cpp
1755 lines (1490 loc) · 56.3 KB
/
test_coro_http_server.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
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 <chrono>
#include <cstdio>
#include <fstream>
#include <future>
#include <iostream>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <system_error>
#include <thread>
#include <vector>
#include "async_simple/coro/Lazy.h"
#include "async_simple/coro/SyncAwait.h"
#include "cinatra/coro_http_client.hpp"
#include "cinatra/coro_http_connection.hpp"
#include "cinatra/coro_http_server.hpp"
#include "cinatra/define.h"
#include "cinatra/response_cv.hpp"
#include "cinatra/utils.hpp"
#include "cinatra/ylt/coro_io/coro_io.hpp"
#include "cinatra/ylt/coro_io/io_context_pool.hpp"
#include "doctest/doctest.h"
using namespace cinatra;
using namespace std::chrono_literals;
TEST_CASE("test parse ranges") {
bool is_valid = true;
auto vec = parse_ranges("200-999", 10000, is_valid);
CHECK(is_valid);
CHECK(vec == std::vector<std::pair<int, int>>{{200, 999}});
vec = parse_ranges("-", 10000, is_valid);
CHECK(is_valid);
CHECK(vec == std::vector<std::pair<int, int>>{{0, 9999}});
vec = parse_ranges("-a", 10000, is_valid);
CHECK(!is_valid);
CHECK(vec.empty());
vec = parse_ranges("--100", 10000, is_valid);
CHECK(!is_valid);
CHECK(vec.empty());
vec = parse_ranges("abc", 10000, is_valid);
CHECK(!is_valid);
CHECK(vec.empty());
is_valid = true;
vec = parse_ranges("-900", 10000, is_valid);
CHECK(is_valid);
CHECK(vec == std::vector<std::pair<int, int>>{{9100, 9999}});
vec = parse_ranges("900", 10000, is_valid);
CHECK(is_valid);
CHECK(vec == std::vector<std::pair<int, int>>{{900, 9999}});
vec = parse_ranges("200-999, 2000-2499", 10000, is_valid);
CHECK(is_valid);
CHECK(vec == std::vector<std::pair<int, int>>{{200, 999}, {2000, 2499}});
vec = parse_ranges("200-999, 2000-2499, 9500-", 10000, is_valid);
CHECK(is_valid);
CHECK(vec == std::vector<std::pair<int, int>>{
{200, 999}, {2000, 2499}, {9500, 9999}});
vec = parse_ranges("", 10000, is_valid);
CHECK(is_valid);
CHECK(vec == std::vector<std::pair<int, int>>{{0, 9999}});
}
TEST_CASE("coro_io post") {
auto t1 = async_simple::coro::syncAwait(coro_io::post([] {
}));
CHECK(!t1.hasError());
auto t2 = async_simple::coro::syncAwait(coro_io::post([] {
throw std::invalid_argument("e");
}));
CHECK(t2.hasError());
auto t3 = async_simple::coro::syncAwait(coro_io::post([] {
return 1;
}));
int r3 = t3.value();
CHECK(r3 == 1);
auto t4 = async_simple::coro::syncAwait(coro_io::post([] {
throw std::invalid_argument("e");
return 1;
}));
CHECK(t4.hasError());
try {
std::rethrow_exception(t4.getException());
} catch (const std::exception &e) {
CHECK(e.what() == std::string("e"));
std::cout << e.what() << "\n";
}
}
TEST_CASE("coro_server example, will block") {
return; // remove this line when you run the coro server.
cinatra::coro_http_server server(std::thread::hardware_concurrency(), 9001);
server.set_http_handler<cinatra::GET, cinatra::POST>(
"/", [](coro_http_request &req, coro_http_response &resp) {
// response in io thread.
std::this_thread::sleep_for(10ms);
resp.set_status_and_content(cinatra::status_type::ok, "hello world");
});
server.set_http_handler<cinatra::GET>(
"/coro",
[](coro_http_request &req,
coro_http_response &resp) -> async_simple::coro::Lazy<void> {
co_await coro_io::post([&]() {
// coroutine in other thread.
std::this_thread::sleep_for(10ms);
resp.set_status_and_content(cinatra::status_type::ok, "hello world");
});
co_return;
});
server.set_http_handler<cinatra::GET, cinatra::POST>(
"/echo", [](coro_http_request &req, coro_http_response &resp) {
// response in io thread.
resp.set_status_and_content(cinatra::status_type::ok, "hello world");
});
server.sync_start();
CHECK(server.port() > 0);
}
template <typename View>
bool create_file(View filename, size_t file_size = 1024) {
std::cout << "begin to open file: " << filename << "\n";
std::ofstream out(filename, std::ios::binary);
if (!out.is_open()) {
std::cout << "open file: " << filename << " failed\n";
return false;
}
std::cout << "open file: " << filename << " ok\n";
std::string str(file_size, 'A');
out.write(str.data(), str.size());
return true;
}
TEST_CASE("test redirect") {
coro_http_server server(1, 9001);
server.set_http_handler<GET>(
"/", [](coro_http_request &req, coro_http_response &resp) {
resp.redirect("/test");
});
server.set_http_handler<GET>(
"/test", [](coro_http_request &req, coro_http_response &resp) {
resp.set_status_and_content(status_type::ok, "redirect ok");
});
server.async_start();
coro_http_client client{};
auto result = client.get("http://127.0.0.1:9001/");
CHECK(result.status == 302);
for (auto [k, v] : result.resp_headers) {
if (k == "Location") {
auto r = client.get(std::string(v));
CHECK(r.resp_body == "redirect ok");
break;
}
}
}
TEST_CASE("test post") {
cinatra::coro_http_server server(1, 9001);
server.set_http_handler<cinatra::GET, cinatra::POST>(
"/echo",
[](coro_http_request &req,
coro_http_response &resp) -> async_simple::coro::Lazy<void> {
resp.set_status_and_content(status_type::ok,
std::string(req.get_body()));
co_return;
});
server.async_start();
std::this_thread::sleep_for(200ms);
coro_http_client client{};
std::string str = "test";
auto r =
client.post("http://127.0.0.1:9001/echo", str, req_content_type::text);
CHECK(r.status == 200);
CHECK(r.resp_body == "test");
r = client.post("/echo", "", req_content_type::text);
CHECK(r.status == 200);
CHECK(r.resp_body == "");
}
TEST_CASE("test multiple download") {
coro_http_server server(1, 9001);
server.set_http_handler<GET>(
"/",
[](coro_http_request &req,
coro_http_response &resp) -> async_simple::coro::Lazy<void> {
// multipart_reader_t multipart(resp.get_conn());
bool ok;
if (ok = co_await resp.get_conn()->begin_multipart(); !ok) {
co_return;
}
std::vector<std::string> vec{"hello", " world", " chunked"};
for (auto &str : vec) {
if (ok = co_await resp.get_conn()->write_multipart(str, "text/plain");
!ok) {
co_return;
}
}
ok = co_await resp.get_conn()->end_multipart();
});
server.set_http_handler<GET>(
"/multipart",
[](coro_http_request &req,
coro_http_response &resp) -> async_simple::coro::Lazy<void> {
bool ok;
if (ok = co_await resp.get_conn()->begin_multipart(); !ok) {
co_return;
}
std::vector<std::string> vec{"hello", " world", " multipart"};
for (auto &str : vec) {
if (ok = co_await resp.get_conn()->write_multipart(str, "text/plain");
!ok) {
co_return;
}
}
ok = co_await resp.get_conn()->end_multipart();
});
server.async_start();
coro_http_client client{};
auto result = client.get("http://127.0.0.1:9001/");
CHECK(result.status == 200);
CHECK(result.resp_body == "hello world chunked");
result = client.get("http://127.0.0.1:9001/multipart");
CHECK(result.status == 200);
CHECK(result.resp_body == "hello world multipart");
}
TEST_CASE("test range download") {
create_file("range_test.txt", 64);
#ifdef ASIO_WINDOWS
#else
create_file("中文测试.txt", 64);
create_file(fs::path(u8"utf8中文.txt").string(), 64);
#endif
std::cout << fs::current_path() << "\n";
coro_http_server server(1, 9001);
server.set_static_res_dir("", "");
server.set_file_resp_format_type(file_resp_format_type::range);
server.async_start();
std::this_thread::sleep_for(300ms);
#ifdef ASIO_WINDOWS
#else
{
// test Chinese file name
coro_http_client client{};
std::string local_filename = "temp.txt";
std::string base_uri = "http://127.0.0.1:9001/";
std::string path = code_utils::url_encode("中文测试.txt");
auto result = client.download(base_uri + path, local_filename);
CHECK(result.status == 200);
CHECK(fs::file_size(local_filename) == 64);
}
{
coro_http_client client{};
std::string local_filename = "temp1.txt";
std::string base_uri = "http://127.0.0.1:9001/";
std::string path =
code_utils::url_encode(fs::path(u8"utf8中文.txt").string());
auto result = client.download(base_uri + path, local_filename);
CHECK(result.status == 200);
CHECK(fs::file_size(local_filename) == 64);
}
#endif
coro_http_client client{};
std::string filename = "test1.txt";
std::error_code ec{};
std::filesystem::remove(filename, ec);
std::string uri = "http://127.0.0.1:9001/range_test.txt";
resp_data result = async_simple::coro::syncAwait(
client.async_download(uri, filename, "1-16"));
CHECK(result.status == 206);
CHECK(fs::file_size(filename) == 16);
filename = "test2.txt";
result = async_simple::coro::syncAwait(
client.async_download(uri, filename, "0-63"));
CHECK(result.status == 200);
CHECK(fs::file_size(filename) == 64);
filename = "test2.txt";
result = async_simple::coro::syncAwait(
client.async_download(uri, filename, "-10"));
CHECK(result.status == 206);
CHECK(fs::file_size(filename) == 10);
filename = "test2.txt";
result = async_simple::coro::syncAwait(
client.async_download(uri, filename, "0-200"));
CHECK(result.status == 200);
CHECK(fs::file_size(filename) == 64);
filename = "test3.txt";
result = async_simple::coro::syncAwait(
client.async_download(uri, filename, "100-200"));
CHECK(result.status == 416);
result = async_simple::coro::syncAwait(
client.async_download(uri, filename, "aaa-200"));
CHECK(result.status == 416);
}
class my_object {
public:
void normal(coro_http_request &req, coro_http_response &response) {
response.set_status_and_content(status_type::ok, "ok");
}
async_simple::coro::Lazy<void> lazy(coro_http_request &req,
coro_http_response &response) {
response.set_status_and_content(status_type::ok, "ok lazy");
co_return;
}
};
TEST_CASE("set http handler") {
cinatra::coro_http_server server(1, 9001);
auto &router = server.get_router();
auto &handlers = router.get_handlers();
server.set_http_handler<cinatra::GET>(
"/", [](coro_http_request &req, coro_http_response &response) {
response.set_status_and_content(status_type::ok, "ok");
});
CHECK(handlers.size() == 1);
server.set_http_handler<cinatra::GET>(
"/", [](coro_http_request &req, coro_http_response &response) {
response.set_status_and_content(status_type::ok, "ok");
});
CHECK(handlers.size() == 1);
server.set_http_handler<cinatra::GET>(
"/aa", [](coro_http_request &req, coro_http_response &response) {
response.set_status_and_content(status_type::ok, "ok");
});
CHECK(handlers.size() == 2);
server.set_http_handler<cinatra::GET, cinatra::POST>(
"/bb", [](coro_http_request &req, coro_http_response &response) {
response.set_status_and_content(status_type::ok, "ok");
});
CHECK(handlers.size() == 4);
cinatra::coro_http_server server2(1, 9001);
server2.set_http_handler<cinatra::GET>(
"/", [](coro_http_request &req, coro_http_response &response) {
response.set_status_and_content(status_type::ok, "ok");
});
auto &handlers2 = server2.get_router().get_handlers();
CHECK(handlers2.size() == 1);
my_object o{};
// member function
server2.set_http_handler<GET>("/test", &my_object::normal, o);
server2.set_http_handler<GET>("/test_lazy", &my_object::lazy, o);
CHECK(handlers2.size() == 2);
auto coro_func =
[](coro_http_request &req,
coro_http_response &response) -> async_simple::coro::Lazy<void> {
response.set_status_and_content(status_type::ok, "ok");
co_return;
};
auto &coro_handlers = router.get_coro_handlers();
server.set_http_handler<cinatra::GET>("/", coro_func);
CHECK(coro_handlers.size() == 1);
server.set_http_handler<cinatra::GET>("/", coro_func);
CHECK(coro_handlers.size() == 1);
server.set_http_handler<cinatra::GET>("/aa", coro_func);
CHECK(coro_handlers.size() == 2);
server.set_http_handler<cinatra::GET, cinatra::POST>("/bb", coro_func);
CHECK(coro_handlers.size() == 4);
}
TEST_CASE("test server start and stop") {
cinatra::coro_http_server server(1, 9000);
auto future = server.async_start();
cinatra::coro_http_server server2(1, 9000);
auto future2 = server2.async_start();
future2.wait();
auto ec = future2.value();
CHECK(ec == asio::error::address_in_use);
}
TEST_CASE("test server sync_start and stop") {
cinatra::coro_http_server server(1, 0);
std::promise<void> promise;
std::error_code ec;
std::thread thd([&] {
promise.set_value();
ec = server.sync_start();
});
promise.get_future().wait();
std::this_thread::sleep_for(std::chrono::milliseconds(200));
server.stop();
thd.join();
CHECK(server.port() > 0);
CHECK(ec == asio::error::operation_aborted);
}
TEST_CASE("get post") {
cinatra::coro_http_server server(1, 9001);
server.set_shrink_to_fit(true);
server.set_http_handler<cinatra::GET, cinatra::POST>(
"/test", [](coro_http_request &req, coro_http_response &resp) {
auto value = req.get_header_value("connection");
CHECK(!value.empty());
auto value1 = req.get_header_value("connection1");
CHECK(value1.empty());
auto value2 = req.get_query_value("aa");
CHECK(value2 == "1");
auto value3 = req.get_query_value("bb");
CHECK(value3 == "test");
auto value4 = req.get_query_value("cc");
CHECK(value4.empty());
auto headers = req.get_headers();
CHECK(!headers.empty());
auto queries = req.get_queries();
CHECK(!queries.empty());
resp.set_keepalive(true);
resp.set_status_and_content(cinatra::status_type::ok, "hello world");
});
server.set_http_handler<cinatra::GET, cinatra::POST>(
"/test1", [](coro_http_request &req, coro_http_response &resp) {
CHECK(req.get_method() == "POST");
CHECK(req.get_url() == "/test1");
CHECK(req.get_conn()->local_address() == "127.0.0.1:9001");
CHECK(req.get_conn()->remote_address().find("127.0.0.1:") !=
std::string::npos);
CHECK(req.get_conn()->remote_address().find("127.0.0.1:") !=
std::string::npos);
resp.add_header("Host", "Cinatra");
resp.set_status_and_content(cinatra::status_type::ok, "hello world");
});
server.set_http_handler<cinatra::GET>(
"/test_coro",
[](coro_http_request &req,
coro_http_response &resp) -> async_simple::coro::Lazy<void> {
co_await coro_io::post([&] {
resp.set_status(cinatra::status_type::ok);
resp.set_content("hello world in coro");
});
});
server.set_http_handler<cinatra::GET, cinatra::POST>(
"/empty", [](coro_http_request &req, coro_http_response &resp) {
resp.add_header("Host", "Cinatra");
resp.set_status_and_content(cinatra::status_type::ok, "");
});
server.set_http_handler<cinatra::GET, cinatra::POST>(
"/close", [](coro_http_request &req, coro_http_response &resp) {
resp.set_keepalive(false);
resp.set_status_and_content(cinatra::status_type::ok, "hello");
resp.get_conn()->close();
auto s = req.get_conn()->local_address();
CHECK(s.empty());
});
server.async_start();
std::this_thread::sleep_for(200ms);
coro_http_client client{};
resp_data result;
result = client.get("http://127.0.0.1:9001/test?aa=1&bb=test");
CHECK(result.status == 200);
CHECK(result.resp_body == "hello world");
result =
client.post("http://127.0.0.1:9001/test1", "", req_content_type::text);
CHECK(result.status == 200);
CHECK(result.resp_body == "hello world");
result = client.get("http://127.0.0.1:9001/test_coro");
CHECK(result.status == 200);
CHECK(result.resp_body == "hello world in coro");
result = client.get("http://127.0.0.1:9001/not_exist");
CHECK(result.status == 404);
result = client.get("http://127.0.0.1:9001/empty");
CHECK(result.status == 200);
auto &headers = result.resp_headers;
auto it =
std::find_if(headers.begin(), headers.end(), [](http_header &header) {
return header.name == "Host" && header.value == "Cinatra";
});
CHECK(it != headers.end());
CHECK(result.resp_body.empty());
client.add_header("Connection", "close");
result = client.get("http://127.0.0.1:9001/close");
CHECK(result.status != 200);
server.stop();
}
TEST_CASE("test alias") {
http_server server(1, 9001);
server.set_http_handler<GET>("/", [](request &req, response &resp) {
resp.set_status_and_content(status_type::ok, "ok");
});
server.async_start();
std::this_thread::sleep_for(300ms);
coro_http_client client{};
auto result = client.get("http://127.0.0.1:9001/");
CHECK(result.resp_body == "ok");
}
struct log_t {
bool before(coro_http_request &, coro_http_response &) {
std::cout << "before log" << std::endl;
return true;
}
bool after(coro_http_request &, coro_http_response &res) {
std::cout << "after log" << std::endl;
res.add_header("aaaa", "bbcc");
return true;
}
};
struct check_t {
bool before(coro_http_request &, coro_http_response &) {
std::cout << "check before" << std::endl;
return true;
}
};
struct check_t1 {
bool before(coro_http_request &, coro_http_response &resp) {
std::cout << "check1 before" << std::endl;
resp.set_status_and_content(status_type::bad_request, "check failed");
return false;
}
};
struct get_data {
bool before(coro_http_request &req, coro_http_response &res) {
req.set_aspect_data("hello", "world");
return true;
}
};
TEST_CASE("test aspects") {
coro_http_server server(1, 9001);
server.set_static_res_dir("", "");
server.set_max_size_of_cache_files(100);
create_file("test_aspect.txt", 64); // in cache
create_file("test_file.txt", 200); // not in cache
server.set_static_res_dir("", "", log_t{}, check_t{});
server.set_http_handler<GET, POST>(
"/",
[](coro_http_request &req, coro_http_response &resp) {
resp.add_header("aaaa", "bbcc");
resp.set_status_and_content(status_type::ok, "ok");
},
log_t{}, check_t{});
server.set_http_handler<GET, POST>(
"/aspect",
[](coro_http_request &req,
coro_http_response &resp) -> async_simple::coro::Lazy<void> {
auto &val = req.get_aspect_data();
CHECK(val[0] == "hello");
CHECK(val[1] == "world");
resp.set_status_and_content(status_type::ok, "ok");
co_return;
},
get_data{});
server.set_http_handler<GET, POST>(
"/check1",
[](coro_http_request &req, coro_http_response &resp) {
resp.set_status_and_content(status_type::ok, "ok");
},
check_t1{}, log_t{});
server.async_start();
coro_http_client client{};
auto result = client.get("http://127.0.0.1:9001/");
auto check = [](auto &result) {
bool has_str = false;
for (auto [k, v] : result.resp_headers) {
if (k == "aaaa") {
if (v == "bbcc") {
has_str = true;
}
break;
}
}
CHECK(has_str);
};
check(result);
result = client.get("http://127.0.0.1:9001/test_aspect.txt");
CHECK(result.status == 200);
result = client.get("http://127.0.0.1:9001/test_file.txt");
CHECK(result.status == 200);
result = client.get("http://127.0.0.1:9001/aspect");
CHECK(result.status == 200);
result = client.get("http://127.0.0.1:9001/check1");
CHECK(result.status == 400);
}
TEST_CASE("use out context") {
asio::io_context out_ctx;
auto work = std::make_unique<asio::io_context::work>(out_ctx);
std::thread thd([&] {
out_ctx.run();
});
cinatra::coro_http_server server(out_ctx, 9001);
server.set_http_handler<cinatra::GET, cinatra::POST>(
"/out_ctx", [](coro_http_request &req, coro_http_response &resp) {
resp.set_status_and_content(status_type::ok, "use out ctx");
});
server.async_start();
std::this_thread::sleep_for(200ms);
{
coro_http_client client1{};
auto result = client1.get("http://127.0.0.1:9001/out_ctx");
CHECK(result.status == 200);
CHECK(result.resp_body == "use out ctx");
}
server.stop();
work.reset();
thd.join();
}
TEST_CASE("delay reply, server stop, form-urlencode, qureies, throw") {
cinatra::coro_http_server server(1, 9001);
server.set_http_handler<cinatra::GET, cinatra::POST>(
"/delay2",
[](coro_http_request &req,
coro_http_response &resp) -> async_simple::coro::Lazy<void> {
resp.set_delay(true);
std::this_thread::sleep_for(200ms);
resp.set_status_and_content(status_type::ok, "delay reply in coro");
co_await resp.get_conn()->reply();
});
server.set_http_handler<cinatra::POST>(
"/form-urlencode", [](coro_http_request &req, coro_http_response &resp) {
CHECK(req.get_body() == "theCityName=58367&aa=%22bbb%22");
CHECK(req.get_query_value("theCityName") == "58367");
CHECK(req.get_decode_query_value("aa") == "\"bbb\"");
CHECK(req.get_decode_query_value("no_such-key").empty());
CHECK(!req.is_upgrade());
resp.set_status_and_content(status_type::ok, "form-urlencode");
});
server.set_http_handler<cinatra::GET>(
"/throw", [](coro_http_request &req, coro_http_response &resp) {
CHECK(req.get_boundary().empty());
throw std::invalid_argument("invalid arguments");
resp.set_status_and_content(status_type::ok, "ok");
});
server.set_http_handler<cinatra::GET>(
"/coro_throw",
[](coro_http_request &req,
coro_http_response &resp) -> async_simple::coro::Lazy<void> {
CHECK(req.get_boundary().empty());
throw std::invalid_argument("invalid arguments");
resp.set_status_and_content(status_type::ok, "ok");
co_return;
});
server.set_http_handler<cinatra::GET>(
"/throw1", [](coro_http_request &req, coro_http_response &resp) {
CHECK(req.get_boundary().empty());
throw 1;
resp.set_status_and_content(status_type::ok, "ok");
});
server.set_http_handler<cinatra::GET>(
"/coro_throw1",
[](coro_http_request &req,
coro_http_response &resp) -> async_simple::coro::Lazy<void> {
CHECK(req.get_boundary().empty());
throw 1;
resp.set_status_and_content(status_type::ok, "ok");
co_return;
});
server.async_start();
resp_data result;
coro_http_client client1{};
result = client1.get("http://127.0.0.1:9001/delay2");
CHECK(result.status == 200);
CHECK(result.resp_body == "delay reply in coro");
result = client1.post("http://127.0.0.1:9001/form-urlencode",
"theCityName=58367&aa=%22bbb%22",
req_content_type::form_url_encode);
CHECK(result.status == 200);
CHECK(result.resp_body == "form-urlencode");
result = client1.get("http://127.0.0.1:9001/throw");
CHECK(result.status == 503);
result = client1.get("http://127.0.0.1:9001/coro_throw");
CHECK(result.status == 503);
result = client1.get("http://127.0.0.1:9001/throw1");
CHECK(result.status == 503);
result = client1.get("http://127.0.0.1:9001/coro_throw1");
CHECK(result.status == 503);
server.stop();
std::cout << "ok\n";
}
async_simple::coro::Lazy<resp_data> chunked_upload1(coro_http_client &client) {
std::string filename = "test.txt";
create_file(filename, 1010);
coro_io::coro_file file{};
file.open(filename, std::ios::in);
std::string buf;
detail::resize(buf, 100);
auto fn = [&file, &buf]() -> async_simple::coro::Lazy<read_result> {
auto [ec, size] = co_await file.async_read(buf.data(), buf.size());
co_return read_result{{buf.data(), buf.size()}, file.eof(), ec};
};
auto result = co_await client.async_upload_chunked(
"http://127.0.0.1:9001/chunked"sv, http_method::POST, std::move(fn));
co_return result;
}
TEST_CASE("chunked request") {
cinatra::coro_http_server server(1, 9001);
server.set_http_handler<cinatra::GET, cinatra::POST>(
"/chunked",
[](coro_http_request &req,
coro_http_response &resp) -> async_simple::coro::Lazy<void> {
assert(req.get_content_type() == content_type::chunked);
chunked_result result{};
std::string content;
while (true) {
result = co_await req.get_conn()->read_chunked();
auto size = req.get_conn()->available();
if (result.ec) {
co_return;
}
if (result.eof) {
CHECK(size == 0);
break;
}
CHECK(size >= 0);
content.append(result.data);
}
std::cout << "content size: " << content.size() << "\n";
std::cout << content << "\n";
resp.set_format_type(format_type::chunked);
resp.set_status_and_content(status_type::ok, "chunked ok");
});
server.set_http_handler<cinatra::GET, cinatra::POST>(
"/write_chunked",
[](coro_http_request &req,
coro_http_response &resp) -> async_simple::coro::Lazy<void> {
resp.set_format_type(format_type::chunked);
bool ok;
if (ok = co_await resp.get_conn()->begin_chunked(); !ok) {
co_return;
}
std::vector<std::string> vec{"hello", " world", " ok"};
for (auto &str : vec) {
if (ok = co_await resp.get_conn()->write_chunked(str); !ok) {
co_return;
}
}
ok = co_await resp.get_conn()->end_chunked();
});
server.async_start();
std::this_thread::sleep_for(200ms);
coro_http_client client{};
auto r = async_simple::coro::syncAwait(chunked_upload1(client));
CHECK(r.status == 200);
CHECK(r.resp_body == "chunked ok");
auto ss = std::make_shared<std::stringstream>();
*ss << "hello world";
auto result = async_simple::coro::syncAwait(client.async_upload_chunked(
"http://127.0.0.1:9001/chunked"sv, http_method::POST, ss));
CHECK(result.status == 200);
CHECK(result.resp_body == "chunked ok");
result = client.get("http://127.0.0.1:9001/write_chunked");
CHECK(result.status == 200);
CHECK(result.resp_body == "hello world ok");
}
TEST_CASE("test websocket with chunked") {
int ws_chunk_size = 100;
cinatra::coro_http_server server(1, 9001);
server.set_http_handler<cinatra::GET>(
"/ws_source",
[ws_chunk_size](coro_http_request &req, coro_http_response &resp)
-> async_simple::coro::Lazy<void> {
CHECK(req.get_content_type() == content_type::websocket);
std::string out_str;
websocket_result result{};
while (!result.eof) {
result = co_await req.get_conn()->read_websocket();
if (result.ec) {
break;
}
if (result.type == ws_frame_type::WS_CLOSE_FRAME) {
std::cout << "close frame\n";
CHECK(result.data.empty());
break;
}
std::cout << result.data.size() << "\n";
if (result.data.size() < ws_chunk_size) {
CHECK(result.data.size() == 24);
CHECK(result.eof);
}
else {
CHECK(result.data.size() == ws_chunk_size);
CHECK(!result.eof);
}
out_str.append(result.data);
auto ec = co_await req.get_conn()->write_websocket(result.data);
if (ec) {
continue;
}
}
CHECK(out_str.size() == 1024);
std::cout << out_str << "\n";
});
server.async_start();
coro_http_client client{};
async_simple::coro::syncAwait(
client.connect("ws://127.0.0.1:9001/ws_source"));
std::string filename = "test.tmp";
create_file(filename);
std::ifstream in(filename, std::ios::binary);
std::string str;
str.resize(ws_chunk_size);
auto source_fn = [&]() -> async_simple::coro::Lazy<read_result> {
size_t size = in.read(str.data(), str.size()).gcount();
bool eof = in.eof();
co_return read_result{{str.data(), size}, eof};
};
async_simple::coro::syncAwait(
client.write_websocket(std::move(source_fn), opcode::binary));
auto data = async_simple::coro::syncAwait(client.read_websocket());
if (data.net_err) {
std::cout << "ws_msg net error " << data.net_err.message() << "\n";
return;
}
size_t msg_len = data.resp_body.size();
std::cout << "ws msg len: " << msg_len << std::endl;
CHECK(!data.resp_body.empty());
std::this_thread::sleep_for(300ms);
server.stop();
}
TEST_CASE("test websocket") {
cinatra::coro_http_server server(1, 8003);
server.set_http_handler<cinatra::GET>(
"/ws_echo",
[](coro_http_request &req,
coro_http_response &resp) -> async_simple::coro::Lazy<void> {
CHECK(req.get_content_type() == content_type::websocket);
std::ofstream out_file("test.temp", std::ios::binary);
websocket_result result{};
while (true) {
result = co_await req.get_conn()->read_websocket();
if (result.ec) {
out_file.close();
break;
}
if (result.type == ws_frame_type::WS_CLOSE_FRAME) {
std::cout << "close frame\n";
out_file.close();
break;
}
if (result.type == ws_frame_type::WS_TEXT_FRAME ||
result.type == ws_frame_type::WS_BINARY_FRAME) {
CHECK(!result.data.empty());
std::cout << result.data << "\n";
out_file << result.data;
}
else {
std::cout << result.data << "\n";
if (result.type == ws_frame_type::WS_PING_FRAME ||
result.type == ws_frame_type::WS_PONG_FRAME) {
std::cout << "ping or pong msg\n";
// ping pong frame just need to continue, no need echo anything,
// because framework has reply ping/pong to client automatically.
continue;
}
else {
// error frame
break;
}
}
auto ec = co_await req.get_conn()->write_websocket(result.data);
if (ec) {
break;
}
}
});
server.async_start();
std::this_thread::sleep_for(200ms); // wait for server handle all messages
auto lazy = []() -> async_simple::coro::Lazy<void> {
coro_http_client client{};
auto ret = co_await client.connect("ws://127.0.0.1:8003/ws_echo");
if (ret.status != 101) {
std::cout << ret.net_err.message() << "\n";
}
CHECK(ret.status == 101);
co_await client.write_websocket(std::string_view("test2fdsaf"),
opcode::binary);