test.cc 130 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421
  1. #include <httplib.h>
  2. #include <gtest/gtest.h>
  3. #include <atomic>
  4. #include <chrono>
  5. #include <future>
  6. #include <sstream>
  7. #include <stdexcept>
  8. #include <thread>
  9. #define SERVER_CERT_FILE "./cert.pem"
  10. #define SERVER_CERT2_FILE "./cert2.pem"
  11. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  12. #define CA_CERT_FILE "./ca-bundle.crt"
  13. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  14. #define CLIENT_CA_CERT_DIR "."
  15. #define CLIENT_CERT_FILE "./client.cert.pem"
  16. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  17. using namespace std;
  18. using namespace httplib;
  19. const char *HOST = "localhost";
  20. const int PORT = 1234;
  21. const string LONG_QUERY_VALUE = string(25000, '@');
  22. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  23. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  24. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  25. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  26. const char *key) {
  27. auto it = std::find_if(
  28. files.begin(), files.end(),
  29. [&](const MultipartFormData &file) { return file.name == key; });
  30. if (it != files.end()) { return *it; }
  31. throw std::runtime_error("invalid mulitpart form data name error");
  32. }
  33. #ifdef _WIN32
  34. TEST(StartupTest, WSAStartup) {
  35. WSADATA wsaData;
  36. int ret = WSAStartup(0x0002, &wsaData);
  37. ASSERT_EQ(0, ret);
  38. }
  39. #endif
  40. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  41. string unescapedCharacters = "-_.!~*'()";
  42. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  43. }
  44. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  45. string reservedCharacters = ";,/?:@&=+$";
  46. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  47. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  48. }
  49. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  50. string chineseCharacters = "中国語";
  51. string russianCharacters = "дом";
  52. string brazilianCharacters = "óculos";
  53. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  54. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  55. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  56. "%D0%B4%D0%BE%D0%BC");
  57. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  58. }
  59. TEST(TrimTests, TrimStringTests) {
  60. EXPECT_EQ("abc", detail::trim_copy("abc"));
  61. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  62. EXPECT_TRUE(detail::trim_copy("").empty());
  63. }
  64. TEST(SplitTest, ParseQueryString) {
  65. string s = "key1=val1&key2=val2&key3=val3";
  66. Params dic;
  67. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  68. [&](const char *b, const char *e) {
  69. string key, val;
  70. detail::split(b, e, '=', [&](const char *b, const char *e) {
  71. if (key.empty()) {
  72. key.assign(b, e);
  73. } else {
  74. val.assign(b, e);
  75. }
  76. });
  77. dic.emplace(key, val);
  78. });
  79. EXPECT_EQ("val1", dic.find("key1")->second);
  80. EXPECT_EQ("val2", dic.find("key2")->second);
  81. EXPECT_EQ("val3", dic.find("key3")->second);
  82. }
  83. TEST(SplitTest, ParseInvalidQueryTests) {
  84. {
  85. string s = " ";
  86. Params dict;
  87. detail::parse_query_text(s, dict);
  88. EXPECT_TRUE(dict.empty());
  89. }
  90. {
  91. string s = " = =";
  92. Params dict;
  93. detail::parse_query_text(s, dict);
  94. EXPECT_TRUE(dict.empty());
  95. }
  96. }
  97. TEST(ParseQueryTest, ParseQueryString) {
  98. string s = "key1=val1&key2=val2&key3=val3";
  99. Params dic;
  100. detail::parse_query_text(s, dic);
  101. EXPECT_EQ("val1", dic.find("key1")->second);
  102. EXPECT_EQ("val2", dic.find("key2")->second);
  103. EXPECT_EQ("val3", dic.find("key3")->second);
  104. }
  105. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  106. Params dic;
  107. EXPECT_EQ(detail::params_to_query_str(dic), "");
  108. dic.emplace("key1", "val1");
  109. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  110. dic.emplace("key2", "val2");
  111. dic.emplace("key3", "val3");
  112. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  113. }
  114. TEST(GetHeaderValueTest, DefaultValue) {
  115. Headers headers = {{"Dummy", "Dummy"}};
  116. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  117. EXPECT_STREQ("text/plain", val);
  118. }
  119. TEST(GetHeaderValueTest, DefaultValueInt) {
  120. Headers headers = {{"Dummy", "Dummy"}};
  121. auto val =
  122. detail::get_header_value<uint64_t>(headers, "Content-Length", 0, 100);
  123. EXPECT_EQ(100ull, val);
  124. }
  125. TEST(GetHeaderValueTest, RegularValue) {
  126. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  127. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  128. EXPECT_STREQ("text/html", val);
  129. }
  130. TEST(GetHeaderValueTest, SetContent) {
  131. Response res;
  132. res.set_content("html", "text/html");
  133. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  134. res.set_content("text", "text/plain");
  135. EXPECT_EQ(1, res.get_header_value_count("Content-Type"));
  136. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  137. }
  138. TEST(GetHeaderValueTest, RegularValueInt) {
  139. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  140. auto val =
  141. detail::get_header_value<uint64_t>(headers, "Content-Length", 0, 0);
  142. EXPECT_EQ(100ull, val);
  143. }
  144. TEST(GetHeaderValueTest, Range) {
  145. {
  146. Headers headers = {make_range_header({{1, -1}})};
  147. auto val = detail::get_header_value(headers, "Range", 0, 0);
  148. EXPECT_STREQ("bytes=1-", val);
  149. }
  150. {
  151. Headers headers = {make_range_header({{-1, 1}})};
  152. auto val = detail::get_header_value(headers, "Range", 0, 0);
  153. EXPECT_STREQ("bytes=-1", val);
  154. }
  155. {
  156. Headers headers = {make_range_header({{1, 10}})};
  157. auto val = detail::get_header_value(headers, "Range", 0, 0);
  158. EXPECT_STREQ("bytes=1-10", val);
  159. }
  160. {
  161. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  162. auto val = detail::get_header_value(headers, "Range", 0, 0);
  163. EXPECT_STREQ("bytes=1-10, 100-", val);
  164. }
  165. {
  166. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  167. auto val = detail::get_header_value(headers, "Range", 0, 0);
  168. EXPECT_STREQ("bytes=1-10, 100-200", val);
  169. }
  170. {
  171. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  172. auto val = detail::get_header_value(headers, "Range", 0, 0);
  173. EXPECT_STREQ("bytes=0-0, -1", val);
  174. }
  175. }
  176. TEST(ParseHeaderValueTest, Range) {
  177. {
  178. Ranges ranges;
  179. auto ret = detail::parse_range_header("bytes=1-", ranges);
  180. EXPECT_TRUE(ret);
  181. EXPECT_EQ(1u, ranges.size());
  182. EXPECT_EQ(1u, ranges[0].first);
  183. EXPECT_EQ(-1, ranges[0].second);
  184. }
  185. {
  186. Ranges ranges;
  187. auto ret = detail::parse_range_header("bytes=-1", ranges);
  188. EXPECT_TRUE(ret);
  189. EXPECT_EQ(1u, ranges.size());
  190. EXPECT_EQ(-1, ranges[0].first);
  191. EXPECT_EQ(1u, ranges[0].second);
  192. }
  193. {
  194. Ranges ranges;
  195. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  196. EXPECT_TRUE(ret);
  197. EXPECT_EQ(1u, ranges.size());
  198. EXPECT_EQ(1u, ranges[0].first);
  199. EXPECT_EQ(10u, ranges[0].second);
  200. }
  201. {
  202. Ranges ranges;
  203. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  204. EXPECT_FALSE(ret);
  205. }
  206. {
  207. Ranges ranges;
  208. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  209. EXPECT_TRUE(ret);
  210. EXPECT_EQ(2u, ranges.size());
  211. EXPECT_EQ(1u, ranges[0].first);
  212. EXPECT_EQ(10u, ranges[0].second);
  213. EXPECT_EQ(100u, ranges[1].first);
  214. EXPECT_EQ(-1, ranges[1].second);
  215. }
  216. {
  217. Ranges ranges;
  218. auto ret =
  219. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  220. EXPECT_TRUE(ret);
  221. EXPECT_EQ(3u, ranges.size());
  222. EXPECT_EQ(1u, ranges[0].first);
  223. EXPECT_EQ(10u, ranges[0].second);
  224. EXPECT_EQ(100u, ranges[1].first);
  225. EXPECT_EQ(200u, ranges[1].second);
  226. EXPECT_EQ(300u, ranges[2].first);
  227. EXPECT_EQ(400u, ranges[2].second);
  228. }
  229. }
  230. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  231. Request req;
  232. req.set_header("Accept-Encoding", "gzip");
  233. Response res;
  234. res.set_header("Content-Type", "text/plain");
  235. auto ret = detail::encoding_type(req, res);
  236. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  237. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  238. #else
  239. EXPECT_TRUE(ret == detail::EncodingType::None);
  240. #endif
  241. }
  242. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  243. Request req;
  244. req.set_header("Accept-Encoding", "gzip, deflate, br");
  245. Response res;
  246. res.set_header("Content-Type", "text/plain");
  247. auto ret = detail::encoding_type(req, res);
  248. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  249. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  250. #elif CPPHTTPLIB_ZLIB_SUPPORT
  251. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  252. #else
  253. EXPECT_TRUE(ret == detail::EncodingType::None);
  254. #endif
  255. }
  256. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  257. Request req;
  258. req.set_header("Accept-Encoding", "br;q=1.0, gzip;q=0.8, *;q=0.1");
  259. Response res;
  260. res.set_header("Content-Type", "text/plain");
  261. auto ret = detail::encoding_type(req, res);
  262. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  263. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  264. #elif CPPHTTPLIB_ZLIB_SUPPORT
  265. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  266. #else
  267. EXPECT_TRUE(ret == detail::EncodingType::None);
  268. #endif
  269. }
  270. TEST(BufferStreamTest, read) {
  271. detail::BufferStream strm1;
  272. Stream &strm = strm1;
  273. EXPECT_EQ(5, strm.write("hello"));
  274. char buf[512];
  275. EXPECT_EQ(2, strm.read(buf, 2));
  276. EXPECT_EQ('h', buf[0]);
  277. EXPECT_EQ('e', buf[1]);
  278. EXPECT_EQ(2, strm.read(buf, 2));
  279. EXPECT_EQ('l', buf[0]);
  280. EXPECT_EQ('l', buf[1]);
  281. EXPECT_EQ(1, strm.read(buf, 1));
  282. EXPECT_EQ('o', buf[0]);
  283. EXPECT_EQ(0, strm.read(buf, 1));
  284. }
  285. TEST(ChunkedEncodingTest, FromHTTPWatch) {
  286. auto host = "www.httpwatch.com";
  287. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  288. auto port = 443;
  289. SSLClient cli(host, port);
  290. #else
  291. auto port = 80;
  292. Client cli(host, port);
  293. #endif
  294. cli.set_connection_timeout(2);
  295. auto res =
  296. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  297. ASSERT_TRUE(res);
  298. std::string out;
  299. detail::read_file("./image.jpg", out);
  300. EXPECT_EQ(200, res->status);
  301. EXPECT_EQ(out, res->body);
  302. }
  303. TEST(ChunkedEncodingTest, WithContentReceiver) {
  304. auto host = "www.httpwatch.com";
  305. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  306. auto port = 443;
  307. SSLClient cli(host, port);
  308. #else
  309. auto port = 80;
  310. Client cli(host, port);
  311. #endif
  312. cli.set_connection_timeout(2);
  313. std::string body;
  314. auto res =
  315. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  316. [&](const char *data, size_t data_length) {
  317. body.append(data, data_length);
  318. return true;
  319. });
  320. ASSERT_TRUE(res);
  321. std::string out;
  322. detail::read_file("./image.jpg", out);
  323. EXPECT_EQ(200, res->status);
  324. EXPECT_EQ(out, body);
  325. }
  326. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  327. auto host = "www.httpwatch.com";
  328. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  329. auto port = 443;
  330. SSLClient cli(host, port);
  331. #else
  332. auto port = 80;
  333. Client cli(host, port);
  334. #endif
  335. cli.set_connection_timeout(2);
  336. std::string body;
  337. auto res = cli.Get(
  338. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  339. [&](const Response &response) {
  340. EXPECT_EQ(200, response.status);
  341. return true;
  342. },
  343. [&](const char *data, size_t data_length) {
  344. body.append(data, data_length);
  345. return true;
  346. });
  347. ASSERT_TRUE(res);
  348. std::string out;
  349. detail::read_file("./image.jpg", out);
  350. EXPECT_EQ(200, res->status);
  351. EXPECT_EQ(out, body);
  352. }
  353. TEST(RangeTest, FromHTTPBin) {
  354. auto host = "httpbin.org";
  355. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  356. auto port = 443;
  357. SSLClient cli(host, port);
  358. #else
  359. auto port = 80;
  360. Client cli(host, port);
  361. #endif
  362. cli.set_connection_timeout(5);
  363. {
  364. auto res = cli.Get("/range/32");
  365. ASSERT_TRUE(res);
  366. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  367. EXPECT_EQ(200, res->status);
  368. }
  369. {
  370. Headers headers = {make_range_header({{1, -1}})};
  371. auto res = cli.Get("/range/32", headers);
  372. ASSERT_TRUE(res);
  373. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  374. EXPECT_EQ(206, res->status);
  375. }
  376. {
  377. Headers headers = {make_range_header({{1, 10}})};
  378. auto res = cli.Get("/range/32", headers);
  379. ASSERT_TRUE(res);
  380. EXPECT_EQ("bcdefghijk", res->body);
  381. EXPECT_EQ(206, res->status);
  382. }
  383. {
  384. Headers headers = {make_range_header({{0, 31}})};
  385. auto res = cli.Get("/range/32", headers);
  386. ASSERT_TRUE(res);
  387. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  388. EXPECT_EQ(200, res->status);
  389. }
  390. {
  391. Headers headers = {make_range_header({{0, -1}})};
  392. auto res = cli.Get("/range/32", headers);
  393. ASSERT_TRUE(res);
  394. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  395. EXPECT_EQ(200, res->status);
  396. }
  397. {
  398. Headers headers = {make_range_header({{0, 32}})};
  399. auto res = cli.Get("/range/32", headers);
  400. ASSERT_TRUE(res);
  401. EXPECT_EQ(416, res->status);
  402. }
  403. }
  404. TEST(ConnectionErrorTest, InvalidHost) {
  405. auto host = "-abcde.com";
  406. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  407. auto port = 443;
  408. SSLClient cli(host, port);
  409. #else
  410. auto port = 80;
  411. Client cli(host, port);
  412. #endif
  413. cli.set_connection_timeout(std::chrono::seconds(2));
  414. auto res = cli.Get("/");
  415. ASSERT_TRUE(!res);
  416. EXPECT_EQ(Error::Connection, res.error());
  417. }
  418. TEST(ConnectionErrorTest, InvalidHost2) {
  419. auto host = "httpbin.org/";
  420. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  421. SSLClient cli(host);
  422. #else
  423. Client cli(host);
  424. #endif
  425. cli.set_connection_timeout(std::chrono::seconds(2));
  426. auto res = cli.Get("/");
  427. ASSERT_TRUE(!res);
  428. EXPECT_EQ(Error::Connection, res.error());
  429. }
  430. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  431. auto host = "httpbin.org/";
  432. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  433. SSLClient cli(host);
  434. #else
  435. Client cli(host);
  436. #endif
  437. cli.set_connection_timeout(std::chrono::seconds(2));
  438. auto res = cli.Get("/");
  439. ASSERT_TRUE(!res);
  440. stringstream s;
  441. s << "error code: " << res.error();
  442. EXPECT_EQ("error code: 2", s.str());
  443. }
  444. TEST(ConnectionErrorTest, InvalidPort) {
  445. auto host = "localhost";
  446. auto port = 44380;
  447. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  448. SSLClient cli(host, port);
  449. #else
  450. Client cli(host, port);
  451. #endif
  452. cli.set_connection_timeout(std::chrono::seconds(2));
  453. auto res = cli.Get("/");
  454. ASSERT_TRUE(!res);
  455. EXPECT_EQ(Error::Connection, res.error());
  456. }
  457. TEST(ConnectionErrorTest, Timeout) {
  458. auto host = "google.com";
  459. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  460. auto port = 44380;
  461. SSLClient cli(host, port);
  462. #else
  463. auto port = 8080;
  464. Client cli(host, port);
  465. #endif
  466. cli.set_connection_timeout(std::chrono::seconds(2));
  467. auto res = cli.Get("/");
  468. ASSERT_TRUE(!res);
  469. EXPECT_TRUE(res.error() == Error::Connection);
  470. }
  471. TEST(CancelTest, NoCancel) {
  472. auto host = "httpbin.org";
  473. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  474. auto port = 443;
  475. SSLClient cli(host, port);
  476. #else
  477. auto port = 80;
  478. Client cli(host, port);
  479. #endif
  480. cli.set_connection_timeout(std::chrono::seconds(5));
  481. auto res = cli.Get("/range/32", [](uint64_t, uint64_t) { return true; });
  482. ASSERT_TRUE(res);
  483. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  484. EXPECT_EQ(200, res->status);
  485. }
  486. TEST(CancelTest, WithCancelSmallPayload) {
  487. auto host = "httpbin.org";
  488. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  489. auto port = 443;
  490. SSLClient cli(host, port);
  491. #else
  492. auto port = 80;
  493. Client cli(host, port);
  494. #endif
  495. auto res = cli.Get("/range/32", [](uint64_t, uint64_t) { return false; });
  496. cli.set_connection_timeout(std::chrono::seconds(5));
  497. ASSERT_TRUE(!res);
  498. EXPECT_EQ(Error::Canceled, res.error());
  499. }
  500. TEST(CancelTest, WithCancelLargePayload) {
  501. auto host = "httpbin.org";
  502. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  503. auto port = 443;
  504. SSLClient cli(host, port);
  505. #else
  506. auto port = 80;
  507. Client cli(host, port);
  508. #endif
  509. cli.set_connection_timeout(std::chrono::seconds(5));
  510. uint32_t count = 0;
  511. auto res = cli.Get("/range/65536",
  512. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  513. ASSERT_TRUE(!res);
  514. EXPECT_EQ(Error::Canceled, res.error());
  515. }
  516. TEST(BaseAuthTest, FromHTTPWatch) {
  517. auto host = "httpbin.org";
  518. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  519. auto port = 443;
  520. SSLClient cli(host, port);
  521. #else
  522. auto port = 80;
  523. Client cli(host, port);
  524. #endif
  525. {
  526. auto res = cli.Get("/basic-auth/hello/world");
  527. ASSERT_TRUE(res);
  528. EXPECT_EQ(401, res->status);
  529. }
  530. {
  531. auto res = cli.Get("/basic-auth/hello/world",
  532. {make_basic_authentication_header("hello", "world")});
  533. ASSERT_TRUE(res);
  534. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  535. res->body);
  536. EXPECT_EQ(200, res->status);
  537. }
  538. {
  539. cli.set_basic_auth("hello", "world");
  540. auto res = cli.Get("/basic-auth/hello/world");
  541. ASSERT_TRUE(res);
  542. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  543. res->body);
  544. EXPECT_EQ(200, res->status);
  545. }
  546. {
  547. cli.set_basic_auth("hello", "bad");
  548. auto res = cli.Get("/basic-auth/hello/world");
  549. ASSERT_TRUE(res);
  550. EXPECT_EQ(401, res->status);
  551. }
  552. {
  553. cli.set_basic_auth("bad", "world");
  554. auto res = cli.Get("/basic-auth/hello/world");
  555. ASSERT_TRUE(res);
  556. EXPECT_EQ(401, res->status);
  557. }
  558. }
  559. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  560. TEST(DigestAuthTest, FromHTTPWatch) {
  561. auto host = "httpbin.org";
  562. auto port = 443;
  563. SSLClient cli(host, port);
  564. {
  565. auto res = cli.Get("/digest-auth/auth/hello/world");
  566. ASSERT_TRUE(res);
  567. EXPECT_EQ(401, res->status);
  568. }
  569. {
  570. std::vector<std::string> paths = {
  571. "/digest-auth/auth/hello/world/MD5",
  572. "/digest-auth/auth/hello/world/SHA-256",
  573. "/digest-auth/auth/hello/world/SHA-512",
  574. "/digest-auth/auth-int/hello/world/MD5",
  575. };
  576. cli.set_digest_auth("hello", "world");
  577. for (auto path : paths) {
  578. auto res = cli.Get(path.c_str());
  579. ASSERT_TRUE(res);
  580. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  581. res->body);
  582. EXPECT_EQ(200, res->status);
  583. }
  584. cli.set_digest_auth("hello", "bad");
  585. for (auto path : paths) {
  586. auto res = cli.Get(path.c_str());
  587. ASSERT_TRUE(res);
  588. EXPECT_EQ(401, res->status);
  589. }
  590. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  591. // out. Plese see https://httpbin.org/digest-auth/auth/hello/world
  592. // cli.set_digest_auth("bad", "world");
  593. // for (auto path : paths) {
  594. // auto res = cli.Get(path.c_str());
  595. // ASSERT_TRUE(res);
  596. // EXPECT_EQ(400, res->status);
  597. // }
  598. }
  599. }
  600. #endif
  601. TEST(AbsoluteRedirectTest, Redirect) {
  602. auto host = "nghttp2.org";
  603. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  604. SSLClient cli(host);
  605. #else
  606. Client cli(host);
  607. #endif
  608. cli.set_follow_location(true);
  609. auto res = cli.Get("/httpbin/absolute-redirect/3");
  610. ASSERT_TRUE(res);
  611. EXPECT_EQ(200, res->status);
  612. }
  613. TEST(RedirectTest, Redirect) {
  614. auto host = "nghttp2.org";
  615. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  616. SSLClient cli(host);
  617. #else
  618. Client cli(host);
  619. #endif
  620. cli.set_follow_location(true);
  621. auto res = cli.Get("/httpbin/redirect/3");
  622. ASSERT_TRUE(res);
  623. EXPECT_EQ(200, res->status);
  624. }
  625. TEST(RelativeRedirectTest, Redirect) {
  626. auto host = "nghttp2.org";
  627. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  628. SSLClient cli(host);
  629. #else
  630. Client cli(host);
  631. #endif
  632. cli.set_follow_location(true);
  633. auto res = cli.Get("/httpbin/relative-redirect/3");
  634. ASSERT_TRUE(res);
  635. EXPECT_EQ(200, res->status);
  636. }
  637. TEST(TooManyRedirectTest, Redirect) {
  638. auto host = "nghttp2.org";
  639. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  640. SSLClient cli(host);
  641. #else
  642. Client cli(host);
  643. #endif
  644. cli.set_follow_location(true);
  645. auto res = cli.Get("/httpbin/redirect/21");
  646. ASSERT_TRUE(!res);
  647. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  648. }
  649. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  650. TEST(YahooRedirectTest, Redirect) {
  651. Client cli("yahoo.com");
  652. auto res = cli.Get("/");
  653. ASSERT_TRUE(res);
  654. EXPECT_EQ(301, res->status);
  655. cli.set_follow_location(true);
  656. res = cli.Get("/");
  657. ASSERT_TRUE(res);
  658. EXPECT_EQ(200, res->status);
  659. EXPECT_EQ("https://yahoo.com/", res->location);
  660. }
  661. TEST(HttpsToHttpRedirectTest, Redirect) {
  662. SSLClient cli("nghttp2.org");
  663. cli.set_follow_location(true);
  664. auto res = cli.Get(
  665. "/httpbin/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  666. ASSERT_TRUE(res);
  667. EXPECT_EQ(200, res->status);
  668. }
  669. TEST(HttpsToHttpRedirectTest2, Redirect) {
  670. SSLClient cli("nghttp2.org");
  671. cli.set_follow_location(true);
  672. Params params;
  673. params.emplace("url", "http://www.google.com");
  674. params.emplace("status_code", "302");
  675. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  676. ASSERT_TRUE(res);
  677. EXPECT_EQ(200, res->status);
  678. }
  679. TEST(HttpsToHttpRedirectTest3, Redirect) {
  680. SSLClient cli("nghttp2.org");
  681. cli.set_follow_location(true);
  682. Params params;
  683. params.emplace("url", "http://www.google.com");
  684. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  685. ASSERT_TRUE(res);
  686. EXPECT_EQ(200, res->status);
  687. }
  688. TEST(UrlWithSpace, Redirect) {
  689. SSLClient cli("edge.forgecdn.net");
  690. cli.set_follow_location(true);
  691. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  692. ASSERT_TRUE(res);
  693. EXPECT_EQ(200, res->status);
  694. EXPECT_EQ(18527, res->get_header_value<uint64_t>("Content-Length"));
  695. }
  696. #endif
  697. TEST(RedirectToDifferentPort, Redirect) {
  698. Server svr8080;
  699. Server svr8081;
  700. svr8080.Get("/1", [&](const Request & /*req*/, Response &res) {
  701. res.set_redirect("http://localhost:8081/2");
  702. });
  703. svr8081.Get("/2", [&](const Request & /*req*/, Response &res) {
  704. res.set_content("Hello World!", "text/plain");
  705. });
  706. auto thread8080 = std::thread([&]() { svr8080.listen("localhost", 8080); });
  707. auto thread8081 = std::thread([&]() { svr8081.listen("localhost", 8081); });
  708. while (!svr8080.is_running() || !svr8081.is_running()) {
  709. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  710. }
  711. // Give GET time to get a few messages.
  712. std::this_thread::sleep_for(std::chrono::seconds(1));
  713. Client cli("localhost", 8080);
  714. cli.set_follow_location(true);
  715. auto res = cli.Get("/1");
  716. ASSERT_TRUE(res);
  717. EXPECT_EQ(200, res->status);
  718. EXPECT_EQ("Hello World!", res->body);
  719. svr8080.stop();
  720. svr8081.stop();
  721. thread8080.join();
  722. thread8081.join();
  723. ASSERT_FALSE(svr8080.is_running());
  724. ASSERT_FALSE(svr8081.is_running());
  725. }
  726. TEST(RedirectFromPageWithContent, Redirect) {
  727. Server svr;
  728. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  729. res.set_content("___", "text/plain");
  730. res.set_redirect("/2");
  731. });
  732. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  733. res.set_content("Hello World!", "text/plain");
  734. });
  735. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  736. while (!svr.is_running()) {
  737. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  738. }
  739. // Give GET time to get a few messages.
  740. std::this_thread::sleep_for(std::chrono::seconds(1));
  741. {
  742. Client cli("localhost", PORT);
  743. cli.set_follow_location(true);
  744. std::string body;
  745. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  746. body.append(data, data_length);
  747. return true;
  748. });
  749. ASSERT_TRUE(res);
  750. EXPECT_EQ(200, res->status);
  751. EXPECT_EQ("Hello World!", body);
  752. }
  753. {
  754. Client cli("localhost", PORT);
  755. std::string body;
  756. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  757. body.append(data, data_length);
  758. return true;
  759. });
  760. ASSERT_TRUE(res);
  761. EXPECT_EQ(302, res->status);
  762. EXPECT_EQ("___", body);
  763. }
  764. svr.stop();
  765. th.join();
  766. ASSERT_FALSE(svr.is_running());
  767. }
  768. TEST(RedirectFromPageWithContentIP6, Redirect) {
  769. Server svr;
  770. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  771. res.set_content("___", "text/plain");
  772. // res.set_redirect("/2");
  773. res.set_redirect("http://[::1]:1234/2");
  774. });
  775. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  776. res.set_content("Hello World!", "text/plain");
  777. });
  778. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  779. while (!svr.is_running()) {
  780. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  781. }
  782. // Give GET time to get a few messages.
  783. std::this_thread::sleep_for(std::chrono::seconds(1));
  784. {
  785. Client cli("http://[::1]:1234");
  786. cli.set_follow_location(true);
  787. std::string body;
  788. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  789. body.append(data, data_length);
  790. return true;
  791. });
  792. ASSERT_TRUE(res);
  793. EXPECT_EQ(200, res->status);
  794. EXPECT_EQ("Hello World!", body);
  795. }
  796. {
  797. Client cli("http://[::1]:1234");
  798. std::string body;
  799. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  800. body.append(data, data_length);
  801. return true;
  802. });
  803. ASSERT_TRUE(res);
  804. EXPECT_EQ(302, res->status);
  805. EXPECT_EQ("___", body);
  806. }
  807. svr.stop();
  808. th.join();
  809. ASSERT_FALSE(svr.is_running());
  810. }
  811. TEST(PathUrlEncodeTest, PathUrlEncode) {
  812. Server svr;
  813. svr.Get("/foo", [](const Request &req, Response &res) {
  814. auto a = req.params.find("a");
  815. if (a != req.params.end()) {
  816. res.set_content((*a).second, "text/plain");
  817. res.status = 200;
  818. } else {
  819. res.status = 400;
  820. }
  821. });
  822. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  823. // Give GET time to get a few messages.
  824. std::this_thread::sleep_for(std::chrono::seconds(1));
  825. {
  826. Client cli(HOST, PORT);
  827. cli.set_url_encode(false);
  828. auto res = cli.Get("/foo?a=explicitly+encoded");
  829. ASSERT_TRUE(res);
  830. EXPECT_EQ(200, res->status);
  831. // This expects it back with a space, as the `+` won't have been
  832. // url-encoded, and server-side the params get decoded turning `+`
  833. // into spaces.
  834. EXPECT_EQ("explicitly encoded", res->body);
  835. }
  836. svr.stop();
  837. thread.join();
  838. ASSERT_FALSE(svr.is_running());
  839. }
  840. TEST(BindServerTest, BindDualStack) {
  841. Server svr;
  842. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  843. res.set_content("Hello World!", "text/plain");
  844. });
  845. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  846. // Give GET time to get a few messages.
  847. std::this_thread::sleep_for(std::chrono::seconds(1));
  848. {
  849. Client cli("127.0.0.1", PORT);
  850. auto res = cli.Get("/1");
  851. ASSERT_TRUE(res);
  852. EXPECT_EQ(200, res->status);
  853. EXPECT_EQ("Hello World!", res->body);
  854. }
  855. {
  856. Client cli("::1", PORT);
  857. auto res = cli.Get("/1");
  858. ASSERT_TRUE(res);
  859. EXPECT_EQ(200, res->status);
  860. EXPECT_EQ("Hello World!", res->body);
  861. }
  862. svr.stop();
  863. thread.join();
  864. ASSERT_FALSE(svr.is_running());
  865. }
  866. TEST(BindServerTest, BindAndListenSeparately) {
  867. Server svr;
  868. int port = svr.bind_to_any_port("0.0.0.0");
  869. ASSERT_TRUE(svr.is_valid());
  870. ASSERT_TRUE(port > 0);
  871. svr.stop();
  872. }
  873. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  874. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  875. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  876. CLIENT_CA_CERT_DIR);
  877. int port = svr.bind_to_any_port("0.0.0.0");
  878. ASSERT_TRUE(svr.is_valid());
  879. ASSERT_TRUE(port > 0);
  880. svr.stop();
  881. }
  882. #endif
  883. TEST(ErrorHandlerTest, ContentLength) {
  884. Server svr;
  885. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  886. res.status = 200;
  887. res.set_content("abcdefghijklmnopqrstuvwxyz",
  888. "text/html"); // <= Content-Length still 13
  889. });
  890. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  891. res.set_content("Hello World!\n", "text/plain");
  892. res.status = 524;
  893. });
  894. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  895. // Give GET time to get a few messages.
  896. std::this_thread::sleep_for(std::chrono::seconds(1));
  897. {
  898. Client cli(HOST, PORT);
  899. auto res = cli.Get("/hi");
  900. ASSERT_TRUE(res);
  901. EXPECT_EQ(200, res->status);
  902. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  903. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  904. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  905. }
  906. svr.stop();
  907. thread.join();
  908. ASSERT_FALSE(svr.is_running());
  909. }
  910. TEST(ExceptionHandlerTest, ContentLength) {
  911. Server svr;
  912. svr.set_exception_handler(
  913. [](const Request & /*req*/, Response &res, std::exception & /*e*/) {
  914. res.status = 500;
  915. res.set_content("abcdefghijklmnopqrstuvwxyz",
  916. "text/html"); // <= Content-Length still 13
  917. });
  918. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  919. res.set_content("Hello World!\n", "text/plain");
  920. throw std::runtime_error("abc");
  921. });
  922. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  923. // Give GET time to get a few messages.
  924. std::this_thread::sleep_for(std::chrono::seconds(1));
  925. {
  926. Client cli(HOST, PORT);
  927. auto res = cli.Get("/hi");
  928. ASSERT_TRUE(res);
  929. EXPECT_EQ(500, res->status);
  930. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  931. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  932. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  933. }
  934. svr.stop();
  935. thread.join();
  936. ASSERT_FALSE(svr.is_running());
  937. }
  938. TEST(NoContentTest, ContentLength) {
  939. Server svr;
  940. svr.Get("/hi",
  941. [](const Request & /*req*/, Response &res) { res.status = 204; });
  942. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  943. // Give GET time to get a few messages.
  944. std::this_thread::sleep_for(std::chrono::seconds(1));
  945. {
  946. Client cli(HOST, PORT);
  947. auto res = cli.Get("/hi");
  948. ASSERT_TRUE(res);
  949. EXPECT_EQ(204, res->status);
  950. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  951. }
  952. svr.stop();
  953. thread.join();
  954. ASSERT_FALSE(svr.is_running());
  955. }
  956. TEST(RoutingHandlerTest, PreRoutingHandler) {
  957. Server svr;
  958. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  959. if (req.path == "/routing_handler") {
  960. res.set_header("PRE_ROUTING", "on");
  961. res.set_content("Routing Handler", "text/plain");
  962. return httplib::Server::HandlerResponse::Handled;
  963. }
  964. return httplib::Server::HandlerResponse::Unhandled;
  965. });
  966. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  967. res.set_content("Error", "text/html");
  968. });
  969. svr.set_post_routing_handler([](const Request &req, Response &res) {
  970. if (req.path == "/routing_handler") {
  971. res.set_header("POST_ROUTING", "on");
  972. }
  973. });
  974. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  975. res.set_content("Hello World!\n", "text/plain");
  976. });
  977. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  978. // Give GET time to get a few messages.
  979. std::this_thread::sleep_for(std::chrono::seconds(1));
  980. {
  981. Client cli(HOST, PORT);
  982. auto res = cli.Get("/routing_handler");
  983. ASSERT_TRUE(res);
  984. EXPECT_EQ(200, res->status);
  985. EXPECT_EQ("Routing Handler", res->body);
  986. EXPECT_EQ(1, res->get_header_value_count("PRE_ROUTING"));
  987. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  988. EXPECT_EQ(1, res->get_header_value_count("POST_ROUTING"));
  989. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  990. }
  991. {
  992. Client cli(HOST, PORT);
  993. auto res = cli.Get("/hi");
  994. ASSERT_TRUE(res);
  995. EXPECT_EQ(200, res->status);
  996. EXPECT_EQ("Hello World!\n", res->body);
  997. EXPECT_EQ(0, res->get_header_value_count("PRE_ROUTING"));
  998. EXPECT_EQ(0, res->get_header_value_count("POST_ROUTING"));
  999. }
  1000. {
  1001. Client cli(HOST, PORT);
  1002. auto res = cli.Get("/aaa");
  1003. ASSERT_TRUE(res);
  1004. EXPECT_EQ(404, res->status);
  1005. EXPECT_EQ("Error", res->body);
  1006. EXPECT_EQ(0, res->get_header_value_count("PRE_ROUTING"));
  1007. EXPECT_EQ(0, res->get_header_value_count("POST_ROUTING"));
  1008. }
  1009. svr.stop();
  1010. thread.join();
  1011. ASSERT_FALSE(svr.is_running());
  1012. }
  1013. TEST(InvalidFormatTest, StatusCode) {
  1014. Server svr;
  1015. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1016. res.set_content("Hello World!\n", "text/plain");
  1017. res.status = 9999; // Status should be a three-digit code...
  1018. });
  1019. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1020. // Give GET time to get a few messages.
  1021. std::this_thread::sleep_for(std::chrono::seconds(1));
  1022. {
  1023. Client cli(HOST, PORT);
  1024. auto res = cli.Get("/hi");
  1025. ASSERT_FALSE(res);
  1026. }
  1027. svr.stop();
  1028. thread.join();
  1029. ASSERT_FALSE(svr.is_running());
  1030. }
  1031. class ServerTest : public ::testing::Test {
  1032. protected:
  1033. ServerTest()
  1034. : cli_(HOST, PORT)
  1035. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1036. ,
  1037. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1038. #endif
  1039. {
  1040. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1041. cli_.enable_server_certificate_verification(false);
  1042. #endif
  1043. }
  1044. virtual void SetUp() {
  1045. svr_.set_mount_point("/", "./www");
  1046. svr_.set_mount_point("/mount", "./www2");
  1047. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  1048. svr_.Get("/hi",
  1049. [&](const Request & /*req*/, Response &res) {
  1050. res.set_content("Hello World!", "text/plain");
  1051. })
  1052. .Get("/http_response_splitting",
  1053. [&](const Request & /*req*/, Response &res) {
  1054. res.set_header("a", "1\r\nSet-Cookie: a=1");
  1055. EXPECT_EQ(0, res.headers.size());
  1056. EXPECT_FALSE(res.has_header("a"));
  1057. res.set_header("a", "1\nSet-Cookie: a=1");
  1058. EXPECT_EQ(0, res.headers.size());
  1059. EXPECT_FALSE(res.has_header("a"));
  1060. res.set_header("a", "1\rSet-Cookie: a=1");
  1061. EXPECT_EQ(0, res.headers.size());
  1062. EXPECT_FALSE(res.has_header("a"));
  1063. res.set_header("a\r\nb", "0");
  1064. EXPECT_EQ(0, res.headers.size());
  1065. EXPECT_FALSE(res.has_header("a"));
  1066. res.set_header("a\rb", "0");
  1067. EXPECT_EQ(0, res.headers.size());
  1068. EXPECT_FALSE(res.has_header("a"));
  1069. res.set_header("a\nb", "0");
  1070. EXPECT_EQ(0, res.headers.size());
  1071. EXPECT_FALSE(res.has_header("a"));
  1072. res.set_redirect("1\r\nSet-Cookie: a=1");
  1073. EXPECT_EQ(0, res.headers.size());
  1074. EXPECT_FALSE(res.has_header("Location"));
  1075. })
  1076. .Get("/slow",
  1077. [&](const Request & /*req*/, Response &res) {
  1078. std::this_thread::sleep_for(std::chrono::seconds(2));
  1079. res.set_content("slow", "text/plain");
  1080. })
  1081. .Post("/slowpost",
  1082. [&](const Request & /*req*/, Response &res) {
  1083. std::this_thread::sleep_for(std::chrono::seconds(2));
  1084. res.set_content("slow", "text/plain");
  1085. })
  1086. .Get("/remote_addr",
  1087. [&](const Request &req, Response &res) {
  1088. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  1089. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  1090. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  1091. EXPECT_EQ(req.remote_port,
  1092. std::stoi(req.get_header_value("REMOTE_PORT")));
  1093. res.set_content(remote_addr.c_str(), "text/plain");
  1094. })
  1095. .Get("/endwith%",
  1096. [&](const Request & /*req*/, Response &res) {
  1097. res.set_content("Hello World!", "text/plain");
  1098. })
  1099. .Get("/a\\+\\+b",
  1100. [&](const Request &req, Response &res) {
  1101. ASSERT_TRUE(req.has_param("a +b"));
  1102. auto val = req.get_param_value("a +b");
  1103. res.set_content(val, "text/plain");
  1104. })
  1105. .Get("/", [&](const Request & /*req*/,
  1106. Response &res) { res.set_redirect("/hi"); })
  1107. .Post("/1", [](const Request & /*req*/,
  1108. Response &res) { res.set_redirect("/2", 303); })
  1109. .Get("/2",
  1110. [](const Request & /*req*/, Response &res) {
  1111. res.set_content("redirected.", "text/plain");
  1112. res.status = 200;
  1113. })
  1114. .Post("/person",
  1115. [&](const Request &req, Response &res) {
  1116. if (req.has_param("name") && req.has_param("note")) {
  1117. persons_[req.get_param_value("name")] =
  1118. req.get_param_value("note");
  1119. } else {
  1120. res.status = 400;
  1121. }
  1122. })
  1123. .Put("/person",
  1124. [&](const Request &req, Response &res) {
  1125. if (req.has_param("name") && req.has_param("note")) {
  1126. persons_[req.get_param_value("name")] =
  1127. req.get_param_value("note");
  1128. } else {
  1129. res.status = 400;
  1130. }
  1131. })
  1132. .Get("/person/(.*)",
  1133. [&](const Request &req, Response &res) {
  1134. string name = req.matches[1];
  1135. if (persons_.find(name) != persons_.end()) {
  1136. auto note = persons_[name];
  1137. res.set_content(note, "text/plain");
  1138. } else {
  1139. res.status = 404;
  1140. }
  1141. })
  1142. .Post("/x-www-form-urlencoded-json",
  1143. [&](const Request &req, Response &res) {
  1144. auto json = req.get_param_value("json");
  1145. ASSERT_EQ(JSON_DATA, json);
  1146. res.set_content(json, "appliation/json");
  1147. res.status = 200;
  1148. })
  1149. .Get("/streamed-chunked",
  1150. [&](const Request & /*req*/, Response &res) {
  1151. res.set_chunked_content_provider(
  1152. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  1153. EXPECT_TRUE(sink.is_writable());
  1154. sink.os << "123";
  1155. sink.os << "456";
  1156. sink.os << "789";
  1157. sink.done();
  1158. return true;
  1159. });
  1160. })
  1161. .Get("/streamed-chunked2",
  1162. [&](const Request & /*req*/, Response &res) {
  1163. auto i = new int(0);
  1164. res.set_chunked_content_provider(
  1165. "text/plain",
  1166. [i](size_t /*offset*/, DataSink &sink) {
  1167. EXPECT_TRUE(sink.is_writable());
  1168. switch (*i) {
  1169. case 0: sink.os << "123"; break;
  1170. case 1: sink.os << "456"; break;
  1171. case 2: sink.os << "789"; break;
  1172. case 3: sink.done(); break;
  1173. }
  1174. (*i)++;
  1175. return true;
  1176. },
  1177. [i](bool success) {
  1178. EXPECT_TRUE(success);
  1179. delete i;
  1180. });
  1181. })
  1182. .Get("/streamed",
  1183. [&](const Request & /*req*/, Response &res) {
  1184. res.set_content_provider(
  1185. 6, "text/plain",
  1186. [](size_t offset, size_t /*length*/, DataSink &sink) {
  1187. sink.os << (offset < 3 ? "a" : "b");
  1188. return true;
  1189. });
  1190. })
  1191. .Get("/streamed-with-range",
  1192. [&](const Request & /*req*/, Response &res) {
  1193. auto data = new std::string("abcdefg");
  1194. res.set_content_provider(
  1195. data->size(), "text/plain",
  1196. [data](size_t offset, size_t length, DataSink &sink) {
  1197. EXPECT_TRUE(sink.is_writable());
  1198. size_t DATA_CHUNK_SIZE = 4;
  1199. const auto &d = *data;
  1200. auto out_len =
  1201. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  1202. auto ret =
  1203. sink.write(&d[static_cast<size_t>(offset)], out_len);
  1204. EXPECT_TRUE(ret);
  1205. return true;
  1206. },
  1207. [data](bool success) {
  1208. EXPECT_TRUE(success);
  1209. delete data;
  1210. });
  1211. })
  1212. .Get("/streamed-cancel",
  1213. [&](const Request & /*req*/, Response &res) {
  1214. res.set_content_provider(
  1215. size_t(-1), "text/plain",
  1216. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1217. EXPECT_TRUE(sink.is_writable());
  1218. sink.os << "data_chunk";
  1219. return true;
  1220. });
  1221. })
  1222. .Get("/with-range",
  1223. [&](const Request & /*req*/, Response &res) {
  1224. res.set_content("abcdefg", "text/plain");
  1225. })
  1226. .Post("/chunked",
  1227. [&](const Request &req, Response & /*res*/) {
  1228. EXPECT_EQ(req.body, "dechunked post body");
  1229. })
  1230. .Post("/large-chunked",
  1231. [&](const Request &req, Response & /*res*/) {
  1232. std::string expected(6 * 30 * 1024u, 'a');
  1233. EXPECT_EQ(req.body, expected);
  1234. })
  1235. .Post("/multipart",
  1236. [&](const Request &req, Response & /*res*/) {
  1237. EXPECT_EQ(6u, req.files.size());
  1238. ASSERT_TRUE(!req.has_file("???"));
  1239. ASSERT_TRUE(req.body.empty());
  1240. {
  1241. const auto &file = req.get_file_value("text1");
  1242. EXPECT_TRUE(file.filename.empty());
  1243. EXPECT_EQ("text default", file.content);
  1244. }
  1245. {
  1246. const auto &file = req.get_file_value("text2");
  1247. EXPECT_TRUE(file.filename.empty());
  1248. EXPECT_EQ("aωb", file.content);
  1249. }
  1250. {
  1251. const auto &file = req.get_file_value("file1");
  1252. EXPECT_EQ("hello.txt", file.filename);
  1253. EXPECT_EQ("text/plain", file.content_type);
  1254. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1255. }
  1256. {
  1257. const auto &file = req.get_file_value("file3");
  1258. EXPECT_TRUE(file.filename.empty());
  1259. EXPECT_EQ("application/octet-stream", file.content_type);
  1260. EXPECT_EQ(0u, file.content.size());
  1261. }
  1262. {
  1263. const auto &file = req.get_file_value("file4");
  1264. EXPECT_TRUE(file.filename.empty());
  1265. EXPECT_EQ(0u, file.content.size());
  1266. EXPECT_EQ("application/json tmp-string", file.content_type);
  1267. }
  1268. })
  1269. .Post("/empty",
  1270. [&](const Request &req, Response &res) {
  1271. EXPECT_EQ(req.body, "");
  1272. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  1273. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1274. res.set_content("empty", "text/plain");
  1275. })
  1276. .Post("/empty-no-content-type",
  1277. [&](const Request &req, Response &res) {
  1278. EXPECT_EQ(req.body, "");
  1279. EXPECT_FALSE(req.has_header("Content-Type"));
  1280. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1281. res.set_content("empty-no-content-type", "text/plain");
  1282. })
  1283. .Put("/empty-no-content-type",
  1284. [&](const Request &req, Response &res) {
  1285. EXPECT_EQ(req.body, "");
  1286. EXPECT_FALSE(req.has_header("Content-Type"));
  1287. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1288. res.set_content("empty-no-content-type", "text/plain");
  1289. })
  1290. .Put("/put",
  1291. [&](const Request &req, Response &res) {
  1292. EXPECT_EQ(req.body, "PUT");
  1293. res.set_content(req.body, "text/plain");
  1294. })
  1295. .Put("/put-large",
  1296. [&](const Request &req, Response &res) {
  1297. EXPECT_EQ(req.body, LARGE_DATA);
  1298. res.set_content(req.body, "text/plain");
  1299. })
  1300. .Patch("/patch",
  1301. [&](const Request &req, Response &res) {
  1302. EXPECT_EQ(req.body, "PATCH");
  1303. res.set_content(req.body, "text/plain");
  1304. })
  1305. .Delete("/delete",
  1306. [&](const Request & /*req*/, Response &res) {
  1307. res.set_content("DELETE", "text/plain");
  1308. })
  1309. .Delete("/delete-body",
  1310. [&](const Request &req, Response &res) {
  1311. EXPECT_EQ(req.body, "content");
  1312. res.set_content(req.body, "text/plain");
  1313. })
  1314. .Options(R"(\*)",
  1315. [&](const Request & /*req*/, Response &res) {
  1316. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  1317. })
  1318. .Get("/request-target",
  1319. [&](const Request &req, Response & /*res*/) {
  1320. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  1321. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  1322. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  1323. })
  1324. .Get("/long-query-value",
  1325. [&](const Request &req, Response & /*res*/) {
  1326. EXPECT_EQ(LONG_QUERY_URL, req.target);
  1327. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  1328. })
  1329. .Get("/array-param",
  1330. [&](const Request &req, Response & /*res*/) {
  1331. EXPECT_EQ(3u, req.get_param_value_count("array"));
  1332. EXPECT_EQ("value1", req.get_param_value("array", 0));
  1333. EXPECT_EQ("value2", req.get_param_value("array", 1));
  1334. EXPECT_EQ("value3", req.get_param_value("array", 2));
  1335. })
  1336. .Post("/validate-no-multiple-headers",
  1337. [&](const Request &req, Response & /*res*/) {
  1338. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  1339. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  1340. })
  1341. .Post("/content_receiver",
  1342. [&](const Request &req, Response &res,
  1343. const ContentReader &content_reader) {
  1344. if (req.is_multipart_form_data()) {
  1345. MultipartFormDataItems files;
  1346. content_reader(
  1347. [&](const MultipartFormData &file) {
  1348. files.push_back(file);
  1349. return true;
  1350. },
  1351. [&](const char *data, size_t data_length) {
  1352. files.back().content.append(data, data_length);
  1353. return true;
  1354. });
  1355. EXPECT_EQ(5u, files.size());
  1356. {
  1357. const auto &file = get_file_value(files, "text1");
  1358. EXPECT_TRUE(file.filename.empty());
  1359. EXPECT_EQ("text default", file.content);
  1360. }
  1361. {
  1362. const auto &file = get_file_value(files, "text2");
  1363. EXPECT_TRUE(file.filename.empty());
  1364. EXPECT_EQ("aωb", file.content);
  1365. }
  1366. {
  1367. const auto &file = get_file_value(files, "file1");
  1368. EXPECT_EQ("hello.txt", file.filename);
  1369. EXPECT_EQ("text/plain", file.content_type);
  1370. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1371. }
  1372. {
  1373. const auto &file = get_file_value(files, "file3");
  1374. EXPECT_TRUE(file.filename.empty());
  1375. EXPECT_EQ("application/octet-stream", file.content_type);
  1376. EXPECT_EQ(0u, file.content.size());
  1377. }
  1378. } else {
  1379. std::string body;
  1380. content_reader([&](const char *data, size_t data_length) {
  1381. EXPECT_EQ(data_length, 7);
  1382. body.append(data, data_length);
  1383. return true;
  1384. });
  1385. EXPECT_EQ(body, "content");
  1386. res.set_content(body, "text/plain");
  1387. }
  1388. })
  1389. .Put("/content_receiver",
  1390. [&](const Request & /*req*/, Response &res,
  1391. const ContentReader &content_reader) {
  1392. std::string body;
  1393. content_reader([&](const char *data, size_t data_length) {
  1394. body.append(data, data_length);
  1395. return true;
  1396. });
  1397. EXPECT_EQ(body, "content");
  1398. res.set_content(body, "text/plain");
  1399. })
  1400. .Patch("/content_receiver",
  1401. [&](const Request & /*req*/, Response &res,
  1402. const ContentReader &content_reader) {
  1403. std::string body;
  1404. content_reader([&](const char *data, size_t data_length) {
  1405. body.append(data, data_length);
  1406. return true;
  1407. });
  1408. EXPECT_EQ(body, "content");
  1409. res.set_content(body, "text/plain");
  1410. })
  1411. .Post("/query-string-and-body",
  1412. [&](const Request &req, Response & /*res*/) {
  1413. ASSERT_TRUE(req.has_param("key"));
  1414. EXPECT_EQ(req.get_param_value("key"), "value");
  1415. EXPECT_EQ(req.body, "content");
  1416. })
  1417. .Get("/last-request",
  1418. [&](const Request &req, Response & /*res*/) {
  1419. EXPECT_EQ("close", req.get_header_value("Connection"));
  1420. })
  1421. .Get(R"(/redirect/(\d+))",
  1422. [&](const Request &req, Response &res) {
  1423. auto num = std::stoi(req.matches[1]) + 1;
  1424. std::string url = "/redirect/" + std::to_string(num);
  1425. res.set_redirect(url);
  1426. })
  1427. .Post("/binary",
  1428. [&](const Request &req, Response &res) {
  1429. EXPECT_EQ(4, req.body.size());
  1430. EXPECT_EQ("application/octet-stream",
  1431. req.get_header_value("Content-Type"));
  1432. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1433. res.set_content(req.body, "application/octet-stream");
  1434. })
  1435. .Put("/binary",
  1436. [&](const Request &req, Response &res) {
  1437. EXPECT_EQ(4, req.body.size());
  1438. EXPECT_EQ("application/octet-stream",
  1439. req.get_header_value("Content-Type"));
  1440. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1441. res.set_content(req.body, "application/octet-stream");
  1442. })
  1443. .Patch("/binary",
  1444. [&](const Request &req, Response &res) {
  1445. EXPECT_EQ(4, req.body.size());
  1446. EXPECT_EQ("application/octet-stream",
  1447. req.get_header_value("Content-Type"));
  1448. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1449. res.set_content(req.body, "application/octet-stream");
  1450. })
  1451. .Delete("/binary",
  1452. [&](const Request &req, Response &res) {
  1453. EXPECT_EQ(4, req.body.size());
  1454. EXPECT_EQ("application/octet-stream",
  1455. req.get_header_value("Content-Type"));
  1456. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1457. res.set_content(req.body, "application/octet-stream");
  1458. })
  1459. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  1460. .Get("/compress",
  1461. [&](const Request & /*req*/, Response &res) {
  1462. res.set_content(
  1463. "12345678901234567890123456789012345678901234567890123456789"
  1464. "01234567890123456789012345678901234567890",
  1465. "text/plain");
  1466. })
  1467. .Get("/nocompress",
  1468. [&](const Request & /*req*/, Response &res) {
  1469. res.set_content(
  1470. "12345678901234567890123456789012345678901234567890123456789"
  1471. "01234567890123456789012345678901234567890",
  1472. "application/octet-stream");
  1473. })
  1474. .Post("/compress-multipart",
  1475. [&](const Request &req, Response & /*res*/) {
  1476. EXPECT_EQ(2u, req.files.size());
  1477. ASSERT_TRUE(!req.has_file("???"));
  1478. {
  1479. const auto &file = req.get_file_value("key1");
  1480. EXPECT_TRUE(file.filename.empty());
  1481. EXPECT_EQ("test", file.content);
  1482. }
  1483. {
  1484. const auto &file = req.get_file_value("key2");
  1485. EXPECT_TRUE(file.filename.empty());
  1486. EXPECT_EQ("--abcdefg123", file.content);
  1487. }
  1488. })
  1489. #endif
  1490. ;
  1491. persons_["john"] = "programmer";
  1492. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1493. while (!svr_.is_running()) {
  1494. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1495. }
  1496. }
  1497. virtual void TearDown() {
  1498. svr_.stop();
  1499. if (!request_threads_.empty()) {
  1500. std::this_thread::sleep_for(std::chrono::seconds(1));
  1501. for (auto &t : request_threads_) {
  1502. t.join();
  1503. }
  1504. }
  1505. t_.join();
  1506. }
  1507. map<string, string> persons_;
  1508. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1509. SSLClient cli_;
  1510. SSLServer svr_;
  1511. #else
  1512. Client cli_;
  1513. Server svr_;
  1514. #endif
  1515. thread t_;
  1516. std::vector<thread> request_threads_;
  1517. };
  1518. TEST_F(ServerTest, GetMethod200) {
  1519. auto res = cli_.Get("/hi");
  1520. ASSERT_TRUE(res);
  1521. EXPECT_EQ("HTTP/1.1", res->version);
  1522. EXPECT_EQ(200, res->status);
  1523. EXPECT_EQ("OK", res->reason);
  1524. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1525. EXPECT_EQ(1, res->get_header_value_count("Content-Type"));
  1526. EXPECT_EQ("Hello World!", res->body);
  1527. }
  1528. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  1529. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  1530. ASSERT_TRUE(res);
  1531. EXPECT_EQ("HTTP/1.1", res->version);
  1532. EXPECT_EQ(200, res->status);
  1533. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1534. EXPECT_EQ(1, res->get_header_value_count("Content-Type"));
  1535. EXPECT_EQ("Hello World!", res->body);
  1536. }
  1537. TEST_F(ServerTest, GetMethod302) {
  1538. auto res = cli_.Get("/");
  1539. ASSERT_TRUE(res);
  1540. EXPECT_EQ(302, res->status);
  1541. EXPECT_EQ("/hi", res->get_header_value("Location"));
  1542. }
  1543. TEST_F(ServerTest, GetMethod302Redirect) {
  1544. cli_.set_follow_location(true);
  1545. auto res = cli_.Get("/");
  1546. ASSERT_TRUE(res);
  1547. EXPECT_EQ(200, res->status);
  1548. EXPECT_EQ("Hello World!", res->body);
  1549. EXPECT_EQ("/hi", res->location);
  1550. }
  1551. TEST_F(ServerTest, GetMethod404) {
  1552. auto res = cli_.Get("/invalid");
  1553. ASSERT_TRUE(res);
  1554. EXPECT_EQ(404, res->status);
  1555. }
  1556. TEST_F(ServerTest, HeadMethod200) {
  1557. auto res = cli_.Head("/hi");
  1558. ASSERT_TRUE(res);
  1559. EXPECT_EQ(200, res->status);
  1560. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1561. EXPECT_TRUE(res->body.empty());
  1562. }
  1563. TEST_F(ServerTest, HeadMethod200Static) {
  1564. auto res = cli_.Head("/mount/dir/index.html");
  1565. ASSERT_TRUE(res);
  1566. EXPECT_EQ(200, res->status);
  1567. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1568. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  1569. EXPECT_TRUE(res->body.empty());
  1570. }
  1571. TEST_F(ServerTest, HeadMethod404) {
  1572. auto res = cli_.Head("/invalid");
  1573. ASSERT_TRUE(res);
  1574. EXPECT_EQ(404, res->status);
  1575. EXPECT_TRUE(res->body.empty());
  1576. }
  1577. TEST_F(ServerTest, GetMethodPersonJohn) {
  1578. auto res = cli_.Get("/person/john");
  1579. ASSERT_TRUE(res);
  1580. EXPECT_EQ(200, res->status);
  1581. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1582. EXPECT_EQ("programmer", res->body);
  1583. }
  1584. TEST_F(ServerTest, PostMethod1) {
  1585. auto res = cli_.Get("/person/john1");
  1586. ASSERT_TRUE(res);
  1587. ASSERT_EQ(404, res->status);
  1588. res = cli_.Post("/person", "name=john1&note=coder",
  1589. "application/x-www-form-urlencoded");
  1590. ASSERT_TRUE(res);
  1591. ASSERT_EQ(200, res->status);
  1592. res = cli_.Get("/person/john1");
  1593. ASSERT_TRUE(res);
  1594. ASSERT_EQ(200, res->status);
  1595. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1596. ASSERT_EQ("coder", res->body);
  1597. }
  1598. TEST_F(ServerTest, PostMethod2) {
  1599. auto res = cli_.Get("/person/john2");
  1600. ASSERT_TRUE(res);
  1601. ASSERT_EQ(404, res->status);
  1602. Params params;
  1603. params.emplace("name", "john2");
  1604. params.emplace("note", "coder");
  1605. res = cli_.Post("/person", params);
  1606. ASSERT_TRUE(res);
  1607. ASSERT_EQ(200, res->status);
  1608. res = cli_.Get("/person/john2");
  1609. ASSERT_TRUE(res);
  1610. ASSERT_EQ(200, res->status);
  1611. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1612. ASSERT_EQ("coder", res->body);
  1613. }
  1614. TEST_F(ServerTest, PutMethod3) {
  1615. auto res = cli_.Get("/person/john3");
  1616. ASSERT_TRUE(res);
  1617. ASSERT_EQ(404, res->status);
  1618. Params params;
  1619. params.emplace("name", "john3");
  1620. params.emplace("note", "coder");
  1621. res = cli_.Put("/person", params);
  1622. ASSERT_TRUE(res);
  1623. ASSERT_EQ(200, res->status);
  1624. res = cli_.Get("/person/john3");
  1625. ASSERT_TRUE(res);
  1626. ASSERT_EQ(200, res->status);
  1627. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1628. ASSERT_EQ("coder", res->body);
  1629. }
  1630. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  1631. Params params;
  1632. params.emplace("json", JSON_DATA);
  1633. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  1634. ASSERT_TRUE(res);
  1635. ASSERT_EQ(200, res->status);
  1636. ASSERT_EQ(JSON_DATA, res->body);
  1637. }
  1638. TEST_F(ServerTest, PostEmptyContent) {
  1639. auto res = cli_.Post("/empty", "", "text/plain");
  1640. ASSERT_TRUE(res);
  1641. ASSERT_EQ(200, res->status);
  1642. ASSERT_EQ("empty", res->body);
  1643. }
  1644. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  1645. auto res = cli_.Post("/empty-no-content-type");
  1646. ASSERT_TRUE(res);
  1647. ASSERT_EQ(200, res->status);
  1648. ASSERT_EQ("empty-no-content-type", res->body);
  1649. }
  1650. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  1651. auto res = cli_.Put("/empty-no-content-type");
  1652. ASSERT_TRUE(res);
  1653. ASSERT_EQ(200, res->status);
  1654. ASSERT_EQ("empty-no-content-type", res->body);
  1655. }
  1656. TEST_F(ServerTest, GetMethodDir) {
  1657. auto res = cli_.Get("/dir/");
  1658. ASSERT_TRUE(res);
  1659. EXPECT_EQ(200, res->status);
  1660. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1661. auto body = R"(<html>
  1662. <head>
  1663. </head>
  1664. <body>
  1665. <a href="/dir/test.html">Test</a>
  1666. <a href="/hi">hi</a>
  1667. </body>
  1668. </html>
  1669. )";
  1670. EXPECT_EQ(body, res->body);
  1671. }
  1672. TEST_F(ServerTest, GetMethodDirTest) {
  1673. auto res = cli_.Get("/dir/test.html");
  1674. ASSERT_TRUE(res);
  1675. EXPECT_EQ(200, res->status);
  1676. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1677. EXPECT_EQ("test.html", res->body);
  1678. }
  1679. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  1680. auto res = cli_.Get("/dir/../dir/test.html");
  1681. ASSERT_TRUE(res);
  1682. EXPECT_EQ(200, res->status);
  1683. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1684. EXPECT_EQ("test.html", res->body);
  1685. }
  1686. TEST_F(ServerTest, GetMethodInvalidPath) {
  1687. auto res = cli_.Get("/dir/../test.html");
  1688. ASSERT_TRUE(res);
  1689. EXPECT_EQ(404, res->status);
  1690. }
  1691. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  1692. auto res = cli_.Get("/../www/dir/test.html");
  1693. ASSERT_TRUE(res);
  1694. EXPECT_EQ(404, res->status);
  1695. }
  1696. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  1697. auto res = cli_.Get("/dir/../../www/dir/test.html");
  1698. ASSERT_TRUE(res);
  1699. EXPECT_EQ(404, res->status);
  1700. }
  1701. TEST_F(ServerTest, GetMethodDirMountTest) {
  1702. auto res = cli_.Get("/mount/dir/test.html");
  1703. ASSERT_TRUE(res);
  1704. EXPECT_EQ(200, res->status);
  1705. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1706. EXPECT_EQ("test.html", res->body);
  1707. }
  1708. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  1709. auto res = cli_.Get("/mount/dir/../dir/test.html");
  1710. ASSERT_TRUE(res);
  1711. EXPECT_EQ(200, res->status);
  1712. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1713. EXPECT_EQ("test.html", res->body);
  1714. }
  1715. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  1716. auto res = cli_.Get("/mount/dir/../test.html");
  1717. ASSERT_TRUE(res);
  1718. EXPECT_EQ(404, res->status);
  1719. }
  1720. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  1721. auto res = cli_.Get("/mount/../www2/dir/test.html");
  1722. ASSERT_TRUE(res);
  1723. EXPECT_EQ(404, res->status);
  1724. }
  1725. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  1726. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  1727. ASSERT_TRUE(res);
  1728. EXPECT_EQ(404, res->status);
  1729. }
  1730. TEST_F(ServerTest, PostMethod303) {
  1731. auto res = cli_.Post("/1", "body", "text/plain");
  1732. ASSERT_TRUE(res);
  1733. EXPECT_EQ(303, res->status);
  1734. EXPECT_EQ("/2", res->get_header_value("Location"));
  1735. }
  1736. TEST_F(ServerTest, PostMethod303Redirect) {
  1737. cli_.set_follow_location(true);
  1738. auto res = cli_.Post("/1", "body", "text/plain");
  1739. ASSERT_TRUE(res);
  1740. EXPECT_EQ(200, res->status);
  1741. EXPECT_EQ("redirected.", res->body);
  1742. EXPECT_EQ("/2", res->location);
  1743. }
  1744. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  1745. auto res = cli_.Get("/dir/test.abcde");
  1746. ASSERT_TRUE(res);
  1747. EXPECT_EQ(200, res->status);
  1748. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1749. EXPECT_EQ("abcde", res->body);
  1750. }
  1751. TEST_F(ServerTest, StaticFileRange) {
  1752. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  1753. ASSERT_TRUE(res);
  1754. EXPECT_EQ(206, res->status);
  1755. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  1756. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  1757. EXPECT_EQ(true, res->has_header("Content-Range"));
  1758. EXPECT_EQ(std::string("cd"), res->body);
  1759. }
  1760. TEST_F(ServerTest, InvalidBaseDirMount) {
  1761. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  1762. }
  1763. TEST_F(ServerTest, Binary) {
  1764. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  1765. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  1766. "application/octet-stream");
  1767. ASSERT_TRUE(res);
  1768. ASSERT_EQ(200, res->status);
  1769. ASSERT_EQ(4, res->body.size());
  1770. res = cli_.Put("/binary", binary.data(), binary.size(),
  1771. "application/octet-stream");
  1772. ASSERT_TRUE(res);
  1773. ASSERT_EQ(200, res->status);
  1774. ASSERT_EQ(4, res->body.size());
  1775. res = cli_.Patch("/binary", binary.data(), binary.size(),
  1776. "application/octet-stream");
  1777. ASSERT_TRUE(res);
  1778. ASSERT_EQ(200, res->status);
  1779. ASSERT_EQ(4, res->body.size());
  1780. res = cli_.Delete("/binary", binary.data(), binary.size(),
  1781. "application/octet-stream");
  1782. ASSERT_TRUE(res);
  1783. ASSERT_EQ(200, res->status);
  1784. ASSERT_EQ(4, res->body.size());
  1785. }
  1786. TEST_F(ServerTest, BinaryString) {
  1787. auto binary = std::string("\x00\x01\x02\x03", 4);
  1788. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  1789. ASSERT_TRUE(res);
  1790. ASSERT_EQ(200, res->status);
  1791. ASSERT_EQ(4, res->body.size());
  1792. res = cli_.Put("/binary", binary, "application/octet-stream");
  1793. ASSERT_TRUE(res);
  1794. ASSERT_EQ(200, res->status);
  1795. ASSERT_EQ(4, res->body.size());
  1796. res = cli_.Patch("/binary", binary, "application/octet-stream");
  1797. ASSERT_TRUE(res);
  1798. ASSERT_EQ(200, res->status);
  1799. ASSERT_EQ(4, res->body.size());
  1800. res = cli_.Delete("/binary", binary, "application/octet-stream");
  1801. ASSERT_TRUE(res);
  1802. ASSERT_EQ(200, res->status);
  1803. ASSERT_EQ(4, res->body.size());
  1804. }
  1805. TEST_F(ServerTest, EmptyRequest) {
  1806. auto res = cli_.Get("");
  1807. ASSERT_TRUE(!res);
  1808. EXPECT_EQ(Error::Connection, res.error());
  1809. }
  1810. TEST_F(ServerTest, LongRequest) {
  1811. std::string request;
  1812. for (size_t i = 0; i < 545; i++) {
  1813. request += "/TooLongRequest";
  1814. }
  1815. request += "OK";
  1816. auto res = cli_.Get(request.c_str());
  1817. ASSERT_TRUE(res);
  1818. EXPECT_EQ(404, res->status);
  1819. }
  1820. TEST_F(ServerTest, TooLongRequest) {
  1821. std::string request;
  1822. for (size_t i = 0; i < 545; i++) {
  1823. request += "/TooLongRequest";
  1824. }
  1825. request += "_NG";
  1826. auto res = cli_.Get(request.c_str());
  1827. ASSERT_TRUE(res);
  1828. EXPECT_EQ(414, res->status);
  1829. }
  1830. TEST_F(ServerTest, LongHeader) {
  1831. Request req;
  1832. req.method = "GET";
  1833. req.path = "/hi";
  1834. std::string host_and_port;
  1835. host_and_port += HOST;
  1836. host_and_port += ":";
  1837. host_and_port += std::to_string(PORT);
  1838. req.headers.emplace("Host", host_and_port.c_str());
  1839. req.headers.emplace("Accept", "*/*");
  1840. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1841. req.headers.emplace(
  1842. "Header-Name",
  1843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1854. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1855. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1856. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1858. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1859. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1861. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1871. "@@@@@@@@@@@@@@@@");
  1872. auto res = std::make_shared<Response>();
  1873. auto error = Error::Success;
  1874. auto ret = cli_.send(req, *res, error);
  1875. ASSERT_TRUE(ret);
  1876. EXPECT_EQ(200, res->status);
  1877. }
  1878. TEST_F(ServerTest, LongQueryValue) {
  1879. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  1880. ASSERT_TRUE(res);
  1881. EXPECT_EQ(414, res->status);
  1882. }
  1883. TEST_F(ServerTest, TooLongHeader) {
  1884. Request req;
  1885. req.method = "GET";
  1886. req.path = "/hi";
  1887. std::string host_and_port;
  1888. host_and_port += HOST;
  1889. host_and_port += ":";
  1890. host_and_port += std::to_string(PORT);
  1891. req.headers.emplace("Host", host_and_port.c_str());
  1892. req.headers.emplace("Accept", "*/*");
  1893. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1894. req.headers.emplace(
  1895. "Header-Name",
  1896. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1897. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1898. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1899. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1900. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1901. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1902. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1903. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1904. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1905. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1906. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1907. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1908. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1909. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1910. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1911. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1912. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1913. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1914. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1915. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1916. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1917. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1918. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1919. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1920. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1921. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1922. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1923. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  1924. "@@@@@@@@@@@@@@@@@");
  1925. auto res = std::make_shared<Response>();
  1926. auto error = Error::Success;
  1927. auto ret = cli_.send(req, *res, error);
  1928. ASSERT_TRUE(ret);
  1929. EXPECT_EQ(200, res->status);
  1930. }
  1931. TEST_F(ServerTest, PercentEncoding) {
  1932. auto res = cli_.Get("/e%6edwith%");
  1933. ASSERT_TRUE(res);
  1934. EXPECT_EQ(200, res->status);
  1935. }
  1936. TEST_F(ServerTest, PercentEncodingUnicode) {
  1937. auto res = cli_.Get("/e%u006edwith%");
  1938. ASSERT_TRUE(res);
  1939. EXPECT_EQ(200, res->status);
  1940. }
  1941. TEST_F(ServerTest, InvalidPercentEncoding) {
  1942. auto res = cli_.Get("/%endwith%");
  1943. ASSERT_TRUE(res);
  1944. EXPECT_EQ(404, res->status);
  1945. }
  1946. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  1947. auto res = cli_.Get("/%uendwith%");
  1948. ASSERT_TRUE(res);
  1949. EXPECT_EQ(404, res->status);
  1950. }
  1951. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  1952. auto res = cli_.Get("/hello?aaa=bbb%");
  1953. ASSERT_TRUE(res);
  1954. EXPECT_EQ(404, res->status);
  1955. }
  1956. TEST_F(ServerTest, PlusSignEncoding) {
  1957. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  1958. ASSERT_TRUE(res);
  1959. EXPECT_EQ(200, res->status);
  1960. EXPECT_EQ("a +b", res->body);
  1961. }
  1962. TEST_F(ServerTest, MultipartFormData) {
  1963. MultipartFormDataItems items = {
  1964. {"text1", "text default", "", ""},
  1965. {"text2", "aωb", "", ""},
  1966. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  1967. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  1968. {"file3", "", "", "application/octet-stream"},
  1969. {"file4", "", "", " application/json tmp-string "}};
  1970. auto res = cli_.Post("/multipart", items);
  1971. ASSERT_TRUE(res);
  1972. EXPECT_EQ(200, res->status);
  1973. }
  1974. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  1975. auto res = cli_.Get("/hi");
  1976. ASSERT_TRUE(res);
  1977. EXPECT_EQ(200, res->status);
  1978. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  1979. EXPECT_EQ("Hello World!", res->body);
  1980. }
  1981. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  1982. Request req;
  1983. req.method = "POST";
  1984. req.path = "/chunked";
  1985. std::string host_and_port;
  1986. host_and_port += HOST;
  1987. host_and_port += ":";
  1988. host_and_port += std::to_string(PORT);
  1989. req.headers.emplace("Host", host_and_port.c_str());
  1990. req.headers.emplace("Accept", "*/*");
  1991. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  1992. req.headers.emplace("Content-Type", "text/plain");
  1993. req.headers.emplace("Content-Length", "0");
  1994. req.headers.emplace(
  1995. "Transfer-Encoding",
  1996. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  1997. // Client does not chunk, so make a chunked body manually.
  1998. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  1999. auto res = std::make_shared<Response>();
  2000. auto error = Error::Success;
  2001. auto ret = cli_.send(req, *res, error);
  2002. ASSERT_TRUE(ret);
  2003. EXPECT_EQ(200, res->status);
  2004. }
  2005. TEST_F(ServerTest, GetStreamed2) {
  2006. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  2007. ASSERT_TRUE(res);
  2008. EXPECT_EQ(206, res->status);
  2009. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2010. EXPECT_EQ(std::string("ab"), res->body);
  2011. }
  2012. TEST_F(ServerTest, GetStreamed) {
  2013. auto res = cli_.Get("/streamed");
  2014. ASSERT_TRUE(res);
  2015. EXPECT_EQ(200, res->status);
  2016. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2017. EXPECT_EQ(std::string("aaabbb"), res->body);
  2018. }
  2019. TEST_F(ServerTest, GetStreamedWithRange1) {
  2020. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  2021. ASSERT_TRUE(res);
  2022. EXPECT_EQ(206, res->status);
  2023. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2024. EXPECT_EQ(true, res->has_header("Content-Range"));
  2025. EXPECT_EQ(std::string("def"), res->body);
  2026. }
  2027. TEST_F(ServerTest, GetStreamedWithRange2) {
  2028. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  2029. ASSERT_TRUE(res);
  2030. EXPECT_EQ(206, res->status);
  2031. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2032. EXPECT_EQ(true, res->has_header("Content-Range"));
  2033. EXPECT_EQ(std::string("bcdefg"), res->body);
  2034. }
  2035. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  2036. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  2037. ASSERT_TRUE(res);
  2038. EXPECT_EQ(206, res->status);
  2039. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2040. EXPECT_EQ(true, res->has_header("Content-Range"));
  2041. EXPECT_EQ(std::string("efg"), res->body);
  2042. }
  2043. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  2044. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-9999"}});
  2045. ASSERT_TRUE(res);
  2046. EXPECT_EQ(206, res->status);
  2047. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2048. EXPECT_EQ(true, res->has_header("Content-Range"));
  2049. EXPECT_EQ(std::string("abcdefg"), res->body);
  2050. }
  2051. TEST_F(ServerTest, GetStreamedWithRangeError) {
  2052. auto res = cli_.Get("/streamed-with-range",
  2053. {{"Range", "bytes=92233720368547758079223372036854775806-"
  2054. "92233720368547758079223372036854775807"}});
  2055. ASSERT_TRUE(res);
  2056. EXPECT_EQ(416, res->status);
  2057. }
  2058. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  2059. auto res =
  2060. cli_.Get("/with-range", {{"Range", "bytes=0-9223372036854775807"}});
  2061. EXPECT_EQ(206, res->status);
  2062. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2063. EXPECT_EQ(true, res->has_header("Content-Range"));
  2064. EXPECT_EQ(std::string("abcdefg"), res->body);
  2065. }
  2066. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  2067. auto res =
  2068. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2069. ASSERT_TRUE(res);
  2070. EXPECT_EQ(206, res->status);
  2071. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  2072. EXPECT_EQ(false, res->has_header("Content-Range"));
  2073. EXPECT_EQ(269, res->body.size());
  2074. }
  2075. TEST_F(ServerTest, GetStreamedEndless) {
  2076. uint64_t offset = 0;
  2077. auto res = cli_.Get("/streamed-cancel",
  2078. [&](const char * /*data*/, uint64_t data_length) {
  2079. if (offset < 100) {
  2080. offset += data_length;
  2081. return true;
  2082. }
  2083. return false;
  2084. });
  2085. ASSERT_TRUE(!res);
  2086. EXPECT_EQ(Error::Canceled, res.error());
  2087. }
  2088. TEST_F(ServerTest, ClientStop) {
  2089. std::vector<std::thread> threads;
  2090. for (auto i = 0; i < 3; i++) {
  2091. threads.emplace_back(thread([&]() {
  2092. auto res = cli_.Get("/streamed-cancel",
  2093. [&](const char *, uint64_t) { return true; });
  2094. ASSERT_TRUE(!res);
  2095. EXPECT_TRUE(res.error() == Error::Canceled ||
  2096. res.error() == Error::Read || res.error() == Error::Write);
  2097. }));
  2098. }
  2099. std::this_thread::sleep_for(std::chrono::seconds(2));
  2100. while (cli_.is_socket_open()) {
  2101. cli_.stop();
  2102. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2103. }
  2104. for (auto &t : threads) {
  2105. t.join();
  2106. }
  2107. }
  2108. TEST_F(ServerTest, GetWithRange1) {
  2109. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  2110. ASSERT_TRUE(res);
  2111. EXPECT_EQ(206, res->status);
  2112. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2113. EXPECT_EQ(true, res->has_header("Content-Range"));
  2114. EXPECT_EQ(std::string("def"), res->body);
  2115. }
  2116. TEST_F(ServerTest, GetWithRange2) {
  2117. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  2118. ASSERT_TRUE(res);
  2119. EXPECT_EQ(206, res->status);
  2120. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2121. EXPECT_EQ(true, res->has_header("Content-Range"));
  2122. EXPECT_EQ(std::string("bcdefg"), res->body);
  2123. }
  2124. TEST_F(ServerTest, GetWithRange3) {
  2125. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  2126. ASSERT_TRUE(res);
  2127. EXPECT_EQ(206, res->status);
  2128. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  2129. EXPECT_EQ(true, res->has_header("Content-Range"));
  2130. EXPECT_EQ(std::string("a"), res->body);
  2131. }
  2132. TEST_F(ServerTest, GetWithRange4) {
  2133. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  2134. ASSERT_TRUE(res);
  2135. EXPECT_EQ(206, res->status);
  2136. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2137. EXPECT_EQ(true, res->has_header("Content-Range"));
  2138. EXPECT_EQ(std::string("fg"), res->body);
  2139. }
  2140. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  2141. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  2142. ASSERT_TRUE(res);
  2143. EXPECT_EQ(416, res->status);
  2144. }
  2145. TEST_F(ServerTest, GetWithRangeMultipart) {
  2146. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2147. ASSERT_TRUE(res);
  2148. EXPECT_EQ(206, res->status);
  2149. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  2150. EXPECT_EQ(false, res->has_header("Content-Range"));
  2151. EXPECT_EQ(269, res->body.size());
  2152. }
  2153. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  2154. auto res =
  2155. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  2156. ASSERT_TRUE(res);
  2157. EXPECT_EQ(416, res->status);
  2158. }
  2159. TEST_F(ServerTest, GetStreamedChunked) {
  2160. auto res = cli_.Get("/streamed-chunked");
  2161. ASSERT_TRUE(res);
  2162. EXPECT_EQ(200, res->status);
  2163. EXPECT_EQ(std::string("123456789"), res->body);
  2164. }
  2165. TEST_F(ServerTest, GetStreamedChunked2) {
  2166. auto res = cli_.Get("/streamed-chunked2");
  2167. ASSERT_TRUE(res);
  2168. EXPECT_EQ(200, res->status);
  2169. EXPECT_EQ(std::string("123456789"), res->body);
  2170. }
  2171. TEST_F(ServerTest, LargeChunkedPost) {
  2172. Request req;
  2173. req.method = "POST";
  2174. req.path = "/large-chunked";
  2175. std::string host_and_port;
  2176. host_and_port += HOST;
  2177. host_and_port += ":";
  2178. host_and_port += std::to_string(PORT);
  2179. req.headers.emplace("Host", host_and_port.c_str());
  2180. req.headers.emplace("Accept", "*/*");
  2181. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2182. req.headers.emplace("Content-Type", "text/plain");
  2183. req.headers.emplace("Content-Length", "0");
  2184. req.headers.emplace("Transfer-Encoding", "chunked");
  2185. std::string long_string(30 * 1024u, 'a');
  2186. std::string chunk = "7800\r\n" + long_string + "\r\n";
  2187. // Attempt to make a large enough post to exceed OS buffers, to test that
  2188. // the server handles short reads if the full chunk data isn't available.
  2189. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  2190. auto res = std::make_shared<Response>();
  2191. auto error = Error::Success;
  2192. auto ret = cli_.send(req, *res, error);
  2193. ASSERT_TRUE(ret);
  2194. EXPECT_EQ(200, res->status);
  2195. }
  2196. TEST_F(ServerTest, GetMethodRemoteAddr) {
  2197. auto res = cli_.Get("/remote_addr");
  2198. ASSERT_TRUE(res);
  2199. EXPECT_EQ(200, res->status);
  2200. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2201. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  2202. }
  2203. TEST_F(ServerTest, HTTPResponseSplitting) {
  2204. auto res = cli_.Get("/http_response_splitting");
  2205. ASSERT_TRUE(res);
  2206. EXPECT_EQ(200, res->status);
  2207. }
  2208. TEST_F(ServerTest, SlowRequest) {
  2209. request_threads_.push_back(
  2210. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2211. request_threads_.push_back(
  2212. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2213. request_threads_.push_back(
  2214. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2215. }
  2216. TEST_F(ServerTest, SlowPost) {
  2217. char buffer[64 * 1024];
  2218. memset(buffer, 0x42, sizeof(buffer));
  2219. auto res = cli_.Post(
  2220. "/slowpost", 64 * 1024 * 1024,
  2221. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2222. auto ret = sink.write(buffer, sizeof(buffer));
  2223. EXPECT_TRUE(ret);
  2224. return true;
  2225. },
  2226. "text/plain");
  2227. ASSERT_TRUE(res);
  2228. EXPECT_EQ(200, res->status);
  2229. }
  2230. TEST_F(ServerTest, SlowPostFail) {
  2231. char buffer[64 * 1024];
  2232. memset(buffer, 0x42, sizeof(buffer));
  2233. cli_.set_write_timeout(std::chrono::seconds(0));
  2234. auto res = cli_.Post(
  2235. "/slowpost", 64 * 1024 * 1024,
  2236. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2237. sink.write(buffer, sizeof(buffer));
  2238. return true;
  2239. },
  2240. "text/plain");
  2241. ASSERT_TRUE(!res);
  2242. EXPECT_EQ(Error::Write, res.error());
  2243. }
  2244. TEST_F(ServerTest, Put) {
  2245. auto res = cli_.Put("/put", "PUT", "text/plain");
  2246. ASSERT_TRUE(res);
  2247. EXPECT_EQ(200, res->status);
  2248. EXPECT_EQ("PUT", res->body);
  2249. }
  2250. TEST_F(ServerTest, PutWithContentProvider) {
  2251. auto res = cli_.Put(
  2252. "/put", 3,
  2253. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2254. EXPECT_TRUE(sink.is_writable());
  2255. sink.os << "PUT";
  2256. return true;
  2257. },
  2258. "text/plain");
  2259. ASSERT_TRUE(res);
  2260. EXPECT_EQ(200, res->status);
  2261. EXPECT_EQ("PUT", res->body);
  2262. }
  2263. TEST_F(ServerTest, PostWithContentProviderAbort) {
  2264. auto res = cli_.Post(
  2265. "/post", 42,
  2266. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2267. return false;
  2268. },
  2269. "text/plain");
  2270. ASSERT_TRUE(!res);
  2271. EXPECT_EQ(Error::Canceled, res.error());
  2272. }
  2273. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  2274. auto res = cli_.Put(
  2275. "/put",
  2276. [](size_t /*offset*/, DataSink &sink) {
  2277. EXPECT_TRUE(sink.is_writable());
  2278. sink.os << "PUT";
  2279. sink.done();
  2280. return true;
  2281. },
  2282. "text/plain");
  2283. ASSERT_TRUE(res);
  2284. EXPECT_EQ(200, res->status);
  2285. EXPECT_EQ("PUT", res->body);
  2286. }
  2287. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  2288. auto res = cli_.Post(
  2289. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2290. "text/plain");
  2291. ASSERT_TRUE(!res);
  2292. EXPECT_EQ(Error::Canceled, res.error());
  2293. }
  2294. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2295. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  2296. cli_.set_compress(true);
  2297. auto res = cli_.Put(
  2298. "/put", 3,
  2299. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2300. EXPECT_TRUE(sink.is_writable());
  2301. sink.os << "PUT";
  2302. return true;
  2303. },
  2304. "text/plain");
  2305. ASSERT_TRUE(res);
  2306. EXPECT_EQ(200, res->status);
  2307. EXPECT_EQ("PUT", res->body);
  2308. }
  2309. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  2310. cli_.set_compress(true);
  2311. auto res = cli_.Post(
  2312. "/post", 42,
  2313. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2314. return false;
  2315. },
  2316. "text/plain");
  2317. ASSERT_TRUE(!res);
  2318. EXPECT_EQ(Error::Canceled, res.error());
  2319. }
  2320. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  2321. cli_.set_compress(true);
  2322. auto res = cli_.Put(
  2323. "/put",
  2324. [](size_t /*offset*/, DataSink &sink) {
  2325. EXPECT_TRUE(sink.is_writable());
  2326. sink.os << "PUT";
  2327. sink.done();
  2328. return true;
  2329. },
  2330. "text/plain");
  2331. ASSERT_TRUE(res);
  2332. EXPECT_EQ(200, res->status);
  2333. EXPECT_EQ("PUT", res->body);
  2334. }
  2335. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  2336. cli_.set_compress(true);
  2337. auto res = cli_.Post(
  2338. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2339. "text/plain");
  2340. ASSERT_TRUE(!res);
  2341. EXPECT_EQ(Error::Canceled, res.error());
  2342. }
  2343. TEST_F(ServerTest, PutLargeFileWithGzip) {
  2344. cli_.set_compress(true);
  2345. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  2346. ASSERT_TRUE(res);
  2347. EXPECT_EQ(200, res->status);
  2348. EXPECT_EQ(LARGE_DATA, res->body);
  2349. }
  2350. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  2351. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2352. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  2353. Client cli(s.c_str());
  2354. cli.enable_server_certificate_verification(false);
  2355. #else
  2356. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  2357. Client cli(s.c_str());
  2358. #endif
  2359. cli.set_compress(true);
  2360. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  2361. ASSERT_TRUE(res);
  2362. EXPECT_EQ(200, res->status);
  2363. EXPECT_EQ(LARGE_DATA, res->body);
  2364. EXPECT_EQ(101942u, res.get_request_header_value<uint64_t>("Content-Length"));
  2365. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  2366. }
  2367. TEST_F(ServerTest, PutContentWithDeflate) {
  2368. cli_.set_compress(false);
  2369. Headers headers;
  2370. headers.emplace("Content-Encoding", "deflate");
  2371. // PUT in deflate format:
  2372. auto res = cli_.Put("/put", headers,
  2373. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  2374. ASSERT_TRUE(res);
  2375. EXPECT_EQ(200, res->status);
  2376. EXPECT_EQ("PUT", res->body);
  2377. }
  2378. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  2379. Headers headers;
  2380. headers.emplace("Accept-Encoding", "gzip, deflate");
  2381. auto res = cli_.Get("/streamed-chunked", headers);
  2382. ASSERT_TRUE(res);
  2383. EXPECT_EQ(200, res->status);
  2384. EXPECT_EQ(std::string("123456789"), res->body);
  2385. }
  2386. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  2387. Headers headers;
  2388. headers.emplace("Accept-Encoding", "gzip, deflate");
  2389. auto res = cli_.Get("/streamed-chunked2", headers);
  2390. ASSERT_TRUE(res);
  2391. EXPECT_EQ(200, res->status);
  2392. EXPECT_EQ(std::string("123456789"), res->body);
  2393. }
  2394. TEST(GzipDecompressor, ChunkedDecompression) {
  2395. std::string data;
  2396. for (size_t i = 0; i < 32 * 1024; ++i) {
  2397. data.push_back(static_cast<char>('a' + i % 26));
  2398. }
  2399. std::string compressed_data;
  2400. {
  2401. httplib::detail::gzip_compressor compressor;
  2402. bool result = compressor.compress(
  2403. data.data(), data.size(),
  2404. /*last=*/true, [&](const char *data, size_t size) {
  2405. compressed_data.insert(compressed_data.size(), data, size);
  2406. return true;
  2407. });
  2408. ASSERT_TRUE(result);
  2409. }
  2410. std::string decompressed_data;
  2411. {
  2412. httplib::detail::gzip_decompressor decompressor;
  2413. // Chunk size is chosen specificaly to have a decompressed chunk size equal
  2414. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  2415. size_t chunk_size = 130;
  2416. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  2417. chunk_begin += chunk_size) {
  2418. size_t current_chunk_size =
  2419. std::min(compressed_data.size() - chunk_begin, chunk_size);
  2420. bool result = decompressor.decompress(
  2421. compressed_data.data() + chunk_begin, current_chunk_size,
  2422. [&](const char *data, size_t size) {
  2423. decompressed_data.insert(decompressed_data.size(), data, size);
  2424. return true;
  2425. });
  2426. ASSERT_TRUE(result);
  2427. }
  2428. }
  2429. ASSERT_EQ(data, decompressed_data);
  2430. }
  2431. #endif
  2432. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2433. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  2434. Headers headers;
  2435. headers.emplace("Accept-Encoding", "br");
  2436. auto res = cli_.Get("/streamed-chunked", headers);
  2437. ASSERT_TRUE(res);
  2438. EXPECT_EQ(200, res->status);
  2439. EXPECT_EQ(std::string("123456789"), res->body);
  2440. }
  2441. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  2442. Headers headers;
  2443. headers.emplace("Accept-Encoding", "br");
  2444. auto res = cli_.Get("/streamed-chunked2", headers);
  2445. ASSERT_TRUE(res);
  2446. EXPECT_EQ(200, res->status);
  2447. EXPECT_EQ(std::string("123456789"), res->body);
  2448. }
  2449. #endif
  2450. TEST_F(ServerTest, Patch) {
  2451. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  2452. ASSERT_TRUE(res);
  2453. EXPECT_EQ(200, res->status);
  2454. EXPECT_EQ("PATCH", res->body);
  2455. }
  2456. TEST_F(ServerTest, Delete) {
  2457. auto res = cli_.Delete("/delete");
  2458. ASSERT_TRUE(res);
  2459. EXPECT_EQ(200, res->status);
  2460. EXPECT_EQ("DELETE", res->body);
  2461. }
  2462. TEST_F(ServerTest, DeleteContentReceiver) {
  2463. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  2464. ASSERT_TRUE(res);
  2465. EXPECT_EQ(200, res->status);
  2466. EXPECT_EQ("content", res->body);
  2467. }
  2468. TEST_F(ServerTest, Options) {
  2469. auto res = cli_.Options("*");
  2470. ASSERT_TRUE(res);
  2471. EXPECT_EQ(200, res->status);
  2472. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  2473. EXPECT_TRUE(res->body.empty());
  2474. }
  2475. TEST_F(ServerTest, URL) {
  2476. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  2477. ASSERT_TRUE(res);
  2478. EXPECT_EQ(200, res->status);
  2479. }
  2480. TEST_F(ServerTest, ArrayParam) {
  2481. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  2482. ASSERT_TRUE(res);
  2483. EXPECT_EQ(200, res->status);
  2484. }
  2485. TEST_F(ServerTest, NoMultipleHeaders) {
  2486. Headers headers = {{"Content-Length", "5"}};
  2487. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  2488. "text/plain");
  2489. ASSERT_TRUE(res);
  2490. EXPECT_EQ(200, res->status);
  2491. }
  2492. TEST_F(ServerTest, PostContentReceiver) {
  2493. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2494. ASSERT_TRUE(res);
  2495. ASSERT_EQ(200, res->status);
  2496. ASSERT_EQ("content", res->body);
  2497. }
  2498. TEST_F(ServerTest, PostMulitpartFilsContentReceiver) {
  2499. MultipartFormDataItems items = {
  2500. {"text1", "text default", "", ""},
  2501. {"text2", "aωb", "", ""},
  2502. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2503. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2504. {"file3", "", "", "application/octet-stream"},
  2505. };
  2506. auto res = cli_.Post("/content_receiver", items);
  2507. ASSERT_TRUE(res);
  2508. EXPECT_EQ(200, res->status);
  2509. }
  2510. TEST_F(ServerTest, PostMulitpartPlusBoundary) {
  2511. MultipartFormDataItems items = {
  2512. {"text1", "text default", "", ""},
  2513. {"text2", "aωb", "", ""},
  2514. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2515. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2516. {"file3", "", "", "application/octet-stream"},
  2517. };
  2518. auto boundary = std::string("+++++");
  2519. std::string body;
  2520. for (const auto &item : items) {
  2521. body += "--" + boundary + "\r\n";
  2522. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  2523. if (!item.filename.empty()) {
  2524. body += "; filename=\"" + item.filename + "\"";
  2525. }
  2526. body += "\r\n";
  2527. if (!item.content_type.empty()) {
  2528. body += "Content-Type: " + item.content_type + "\r\n";
  2529. }
  2530. body += "\r\n";
  2531. body += item.content + "\r\n";
  2532. }
  2533. body += "--" + boundary + "--\r\n";
  2534. std::string content_type = "multipart/form-data; boundary=" + boundary;
  2535. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  2536. ASSERT_TRUE(res);
  2537. EXPECT_EQ(200, res->status);
  2538. }
  2539. TEST_F(ServerTest, PostContentReceiverGzip) {
  2540. cli_.set_compress(true);
  2541. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2542. ASSERT_TRUE(res);
  2543. ASSERT_EQ(200, res->status);
  2544. ASSERT_EQ("content", res->body);
  2545. }
  2546. TEST_F(ServerTest, PutContentReceiver) {
  2547. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  2548. ASSERT_TRUE(res);
  2549. ASSERT_EQ(200, res->status);
  2550. ASSERT_EQ("content", res->body);
  2551. }
  2552. TEST_F(ServerTest, PatchContentReceiver) {
  2553. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  2554. ASSERT_TRUE(res);
  2555. ASSERT_EQ(200, res->status);
  2556. ASSERT_EQ("content", res->body);
  2557. }
  2558. TEST_F(ServerTest, PostQueryStringAndBody) {
  2559. auto res =
  2560. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  2561. ASSERT_TRUE(res);
  2562. ASSERT_EQ(200, res->status);
  2563. }
  2564. TEST_F(ServerTest, HTTP2Magic) {
  2565. Request req;
  2566. req.method = "PRI";
  2567. req.path = "*";
  2568. req.body = "SM";
  2569. auto res = std::make_shared<Response>();
  2570. auto error = Error::Success;
  2571. auto ret = cli_.send(req, *res, error);
  2572. ASSERT_TRUE(ret);
  2573. EXPECT_EQ(400, res->status);
  2574. }
  2575. TEST_F(ServerTest, KeepAlive) {
  2576. auto res = cli_.Get("/hi");
  2577. ASSERT_TRUE(res);
  2578. EXPECT_EQ(200, res->status);
  2579. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2580. EXPECT_EQ("Hello World!", res->body);
  2581. res = cli_.Get("/hi");
  2582. ASSERT_TRUE(res);
  2583. EXPECT_EQ(200, res->status);
  2584. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2585. EXPECT_EQ("Hello World!", res->body);
  2586. res = cli_.Get("/hi");
  2587. ASSERT_TRUE(res);
  2588. EXPECT_EQ(200, res->status);
  2589. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2590. EXPECT_EQ("Hello World!", res->body);
  2591. res = cli_.Get("/not-exist");
  2592. ASSERT_TRUE(res);
  2593. EXPECT_EQ(404, res->status);
  2594. res = cli_.Post("/empty", "", "text/plain");
  2595. ASSERT_TRUE(res);
  2596. EXPECT_EQ(200, res->status);
  2597. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2598. EXPECT_EQ("empty", res->body);
  2599. EXPECT_EQ("close", res->get_header_value("Connection"));
  2600. res = cli_.Post(
  2601. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  2602. "text/plain");
  2603. ASSERT_TRUE(res);
  2604. EXPECT_EQ(200, res->status);
  2605. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2606. EXPECT_EQ("empty", res->body);
  2607. cli_.set_keep_alive(false);
  2608. res = cli_.Get("/last-request");
  2609. ASSERT_TRUE(res);
  2610. EXPECT_EQ(200, res->status);
  2611. EXPECT_EQ("close", res->get_header_value("Connection"));
  2612. }
  2613. TEST_F(ServerTest, TooManyRedirect) {
  2614. cli_.set_follow_location(true);
  2615. auto res = cli_.Get("/redirect/0");
  2616. ASSERT_TRUE(!res);
  2617. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2618. }
  2619. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2620. TEST_F(ServerTest, Gzip) {
  2621. Headers headers;
  2622. headers.emplace("Accept-Encoding", "gzip, deflate");
  2623. auto res = cli_.Get("/compress", headers);
  2624. ASSERT_TRUE(res);
  2625. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2626. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2627. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2628. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2629. "7890123456789012345678901234567890",
  2630. res->body);
  2631. EXPECT_EQ(200, res->status);
  2632. }
  2633. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  2634. auto res = cli_.Get("/compress");
  2635. ASSERT_TRUE(res);
  2636. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2637. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2638. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2639. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2640. "7890123456789012345678901234567890",
  2641. res->body);
  2642. EXPECT_EQ(200, res->status);
  2643. }
  2644. TEST_F(ServerTest, GzipWithContentReceiver) {
  2645. Headers headers;
  2646. headers.emplace("Accept-Encoding", "gzip, deflate");
  2647. std::string body;
  2648. auto res = cli_.Get("/compress", headers,
  2649. [&](const char *data, uint64_t data_length) {
  2650. EXPECT_EQ(data_length, 100);
  2651. body.append(data, data_length);
  2652. return true;
  2653. });
  2654. ASSERT_TRUE(res);
  2655. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2656. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2657. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2658. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2659. "7890123456789012345678901234567890",
  2660. body);
  2661. EXPECT_EQ(200, res->status);
  2662. }
  2663. TEST_F(ServerTest, GzipWithoutDecompressing) {
  2664. Headers headers;
  2665. headers.emplace("Accept-Encoding", "gzip, deflate");
  2666. cli_.set_decompress(false);
  2667. auto res = cli_.Get("/compress", headers);
  2668. ASSERT_TRUE(res);
  2669. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2670. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2671. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2672. EXPECT_EQ(33, res->body.size());
  2673. EXPECT_EQ(200, res->status);
  2674. }
  2675. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  2676. std::string body;
  2677. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  2678. EXPECT_EQ(data_length, 100);
  2679. body.append(data, data_length);
  2680. return true;
  2681. });
  2682. ASSERT_TRUE(res);
  2683. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2684. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2685. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2686. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2687. "7890123456789012345678901234567890",
  2688. body);
  2689. EXPECT_EQ(200, res->status);
  2690. }
  2691. TEST_F(ServerTest, NoGzip) {
  2692. Headers headers;
  2693. headers.emplace("Accept-Encoding", "gzip, deflate");
  2694. auto res = cli_.Get("/nocompress", headers);
  2695. ASSERT_TRUE(res);
  2696. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2697. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2698. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2699. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2700. "7890123456789012345678901234567890",
  2701. res->body);
  2702. EXPECT_EQ(200, res->status);
  2703. }
  2704. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  2705. Headers headers;
  2706. headers.emplace("Accept-Encoding", "gzip, deflate");
  2707. std::string body;
  2708. auto res = cli_.Get("/nocompress", headers,
  2709. [&](const char *data, uint64_t data_length) {
  2710. EXPECT_EQ(data_length, 100);
  2711. body.append(data, data_length);
  2712. return true;
  2713. });
  2714. ASSERT_TRUE(res);
  2715. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  2716. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2717. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2718. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2719. "7890123456789012345678901234567890",
  2720. body);
  2721. EXPECT_EQ(200, res->status);
  2722. }
  2723. TEST_F(ServerTest, MultipartFormDataGzip) {
  2724. MultipartFormDataItems items = {
  2725. {"key1", "test", "", ""},
  2726. {"key2", "--abcdefg123", "", ""},
  2727. };
  2728. cli_.set_compress(true);
  2729. auto res = cli_.Post("/compress-multipart", items);
  2730. ASSERT_TRUE(res);
  2731. EXPECT_EQ(200, res->status);
  2732. }
  2733. #endif
  2734. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2735. TEST_F(ServerTest, Brotli) {
  2736. Headers headers;
  2737. headers.emplace("Accept-Encoding", "br");
  2738. auto res = cli_.Get("/compress", headers);
  2739. ASSERT_TRUE(res);
  2740. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  2741. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2742. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  2743. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2744. "7890123456789012345678901234567890",
  2745. res->body);
  2746. EXPECT_EQ(200, res->status);
  2747. }
  2748. #endif
  2749. // Sends a raw request to a server listening at HOST:PORT.
  2750. static bool send_request(time_t read_timeout_sec, const std::string &req,
  2751. std::string *resp = nullptr) {
  2752. auto error = Error::Success;
  2753. auto client_sock = detail::create_client_socket(
  2754. HOST, PORT, AF_UNSPEC, false, nullptr,
  2755. /*connection_timeout_sec=*/5, 0,
  2756. /*read_timeout_sec=*/5, 0,
  2757. /*write_timeout_sec=*/5, 0, std::string(), error);
  2758. if (client_sock == INVALID_SOCKET) { return false; }
  2759. auto ret = detail::process_client_socket(
  2760. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  2761. if (req.size() !=
  2762. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  2763. return false;
  2764. }
  2765. char buf[512];
  2766. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  2767. while (line_reader.getline()) {
  2768. if (resp) { *resp += line_reader.ptr(); }
  2769. }
  2770. return true;
  2771. });
  2772. detail::close_socket(client_sock);
  2773. return ret;
  2774. }
  2775. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  2776. Server svr;
  2777. std::string header_value;
  2778. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  2779. header_value = req.get_header_value("foo");
  2780. res.set_content("ok", "text/plain");
  2781. });
  2782. thread t = thread([&] { svr.listen(HOST, PORT); });
  2783. while (!svr.is_running()) {
  2784. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2785. }
  2786. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  2787. // like characters are not treated the same - use vertical tab and escape.
  2788. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  2789. "foo: \t \v bar \e\t \r\n"
  2790. "Connection: close\r\n"
  2791. "\r\n";
  2792. ASSERT_TRUE(send_request(5, req));
  2793. svr.stop();
  2794. t.join();
  2795. EXPECT_EQ(header_value, "\v bar \e");
  2796. }
  2797. // Sends a raw request and verifies that there isn't a crash or exception.
  2798. static void test_raw_request(const std::string &req,
  2799. std::string *out = nullptr) {
  2800. Server svr;
  2801. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2802. res.set_content("ok", "text/plain");
  2803. });
  2804. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  2805. res.set_content("ok", "text/plain");
  2806. });
  2807. // Server read timeout must be longer than the client read timeout for the
  2808. // bug to reproduce, probably to force the server to process a request
  2809. // without a trailing blank line.
  2810. const time_t client_read_timeout_sec = 1;
  2811. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  2812. bool listen_thread_ok = false;
  2813. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  2814. while (!svr.is_running()) {
  2815. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2816. }
  2817. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  2818. svr.stop();
  2819. t.join();
  2820. EXPECT_TRUE(listen_thread_ok);
  2821. }
  2822. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  2823. // A certain header line causes an exception if the header property is parsed
  2824. // naively with a single regex. This occurs with libc++ but not libstdc++.
  2825. test_raw_request(
  2826. "GET /hi HTTP/1.1\r\n"
  2827. " : "
  2828. " "
  2829. " ");
  2830. }
  2831. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  2832. // A certain header line causes an exception if the header property *name* is
  2833. // parsed with a regular expression starting with "(.+?):" - this is a non-
  2834. // greedy matcher and requires backtracking when there are a lot of ":"
  2835. // characters.
  2836. // This occurs with libc++ but not libstdc++.
  2837. test_raw_request(
  2838. "GET /hi HTTP/1.1\r\n"
  2839. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  2840. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  2841. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  2842. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  2843. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  2844. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  2845. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  2846. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  2847. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  2848. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  2849. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  2850. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  2851. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  2852. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  2853. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  2854. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  2855. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  2856. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  2857. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  2858. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  2859. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  2860. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  2861. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  2862. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  2863. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  2864. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  2865. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  2866. "&&&%%%");
  2867. }
  2868. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparseableHeaderLine) {
  2869. // Make sure this doesn't crash the server.
  2870. // In a previous version of the header line regex, the "\r" rendered the line
  2871. // unparseable and the regex engine repeatedly backtracked, trying to look for
  2872. // a new position where the leading white space ended and the field value
  2873. // began.
  2874. // The crash occurs with libc++ but not libstdc++.
  2875. test_raw_request("GET /hi HTTP/1.1\r\n"
  2876. "a:" +
  2877. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  2878. "\r\n"
  2879. "\r\n");
  2880. }
  2881. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  2882. std::string out;
  2883. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2884. "Content-Type: text/plain\r\n"
  2885. "Transfer-Encoding: chunked\r\n"
  2886. "\r\n"
  2887. "nothex\r\n",
  2888. &out);
  2889. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2890. }
  2891. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  2892. std::string out;
  2893. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2894. "Content-Type: text/plain\r\n"
  2895. "Transfer-Encoding: chunked\r\n"
  2896. "\r\n"
  2897. "3\r\n"
  2898. "xyz\r\n"
  2899. "NaN\r\n",
  2900. &out);
  2901. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2902. }
  2903. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  2904. std::string out;
  2905. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  2906. "Content-Type: text/plain\r\n"
  2907. "Transfer-Encoding: chunked\r\n"
  2908. "\r\n"
  2909. // Length is too large for 64 bits.
  2910. "1ffffffffffffffff\r\n"
  2911. "xyz\r\n",
  2912. &out);
  2913. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2914. }
  2915. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  2916. test_raw_request("GET /hi HTTP/1.1\r\n"
  2917. "Content-Type: text/plain\r\n\r");
  2918. }
  2919. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  2920. std::string out;
  2921. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  2922. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  2923. }
  2924. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  2925. Server svr;
  2926. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  2927. res.set_header("Cache-Control", "no-cache");
  2928. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  2929. DataSink &sink) {
  2930. char buffer[27];
  2931. auto size = static_cast<size_t>(sprintf(buffer, "data:%ld\n\n", offset));
  2932. auto ret = sink.write(buffer, size);
  2933. EXPECT_TRUE(ret);
  2934. std::this_thread::sleep_for(std::chrono::seconds(1));
  2935. return true;
  2936. });
  2937. });
  2938. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2939. while (!svr.is_running()) {
  2940. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2941. }
  2942. Client client(HOST, PORT);
  2943. const Headers headers = {{"Accept", "text/event-stream"}};
  2944. auto get_thread = std::thread([&client, &headers]() {
  2945. auto res = client.Get(
  2946. "/events", headers,
  2947. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  2948. });
  2949. // Give GET time to get a few messages.
  2950. std::this_thread::sleep_for(std::chrono::seconds(2));
  2951. svr.stop();
  2952. listen_thread.join();
  2953. get_thread.join();
  2954. ASSERT_FALSE(svr.is_running());
  2955. }
  2956. TEST(StreamingTest, NoContentLengthStreaming) {
  2957. Server svr;
  2958. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  2959. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  2960. if (offset < 6) {
  2961. sink.os << (offset < 3 ? "a" : "b");
  2962. } else {
  2963. sink.done();
  2964. }
  2965. return true;
  2966. });
  2967. });
  2968. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2969. while (!svr.is_running()) {
  2970. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2971. }
  2972. Client client(HOST, PORT);
  2973. auto get_thread = std::thread([&client]() {
  2974. auto res = client.Get("/stream", [](const char *data, size_t len) -> bool {
  2975. EXPECT_EQ("aaabbb", std::string(data, len));
  2976. return true;
  2977. });
  2978. });
  2979. // Give GET time to get a few messages.
  2980. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  2981. svr.stop();
  2982. listen_thread.join();
  2983. get_thread.join();
  2984. ASSERT_FALSE(svr.is_running());
  2985. }
  2986. TEST(MountTest, Unmount) {
  2987. Server svr;
  2988. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2989. while (!svr.is_running()) {
  2990. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2991. }
  2992. // Give GET time to get a few messages.
  2993. std::this_thread::sleep_for(std::chrono::seconds(1));
  2994. Client cli("localhost", PORT);
  2995. svr.set_mount_point("/mount2", "./www2");
  2996. auto res = cli.Get("/");
  2997. ASSERT_TRUE(res);
  2998. EXPECT_EQ(404, res->status);
  2999. res = cli.Get("/mount2/dir/test.html");
  3000. ASSERT_TRUE(res);
  3001. EXPECT_EQ(200, res->status);
  3002. svr.set_mount_point("/", "./www");
  3003. res = cli.Get("/dir/");
  3004. ASSERT_TRUE(res);
  3005. EXPECT_EQ(200, res->status);
  3006. svr.remove_mount_point("/");
  3007. res = cli.Get("/dir/");
  3008. ASSERT_TRUE(res);
  3009. EXPECT_EQ(404, res->status);
  3010. svr.remove_mount_point("/mount2");
  3011. res = cli.Get("/mount2/dir/test.html");
  3012. ASSERT_TRUE(res);
  3013. EXPECT_EQ(404, res->status);
  3014. svr.stop();
  3015. listen_thread.join();
  3016. ASSERT_FALSE(svr.is_running());
  3017. }
  3018. TEST(ExceptionTest, ThrowExceptionInHandler) {
  3019. Server svr;
  3020. svr.Get("/hi", [&](const Request & /*req*/, Response & /*res*/) {
  3021. throw std::runtime_error("exception...");
  3022. // res.set_content("Hello World!", "text/plain");
  3023. });
  3024. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3025. while (!svr.is_running()) {
  3026. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3027. }
  3028. // Give GET time to get a few messages.
  3029. std::this_thread::sleep_for(std::chrono::seconds(1));
  3030. Client cli("localhost", PORT);
  3031. auto res = cli.Get("/hi");
  3032. ASSERT_TRUE(res);
  3033. EXPECT_EQ(500, res->status);
  3034. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3035. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  3036. svr.stop();
  3037. listen_thread.join();
  3038. ASSERT_FALSE(svr.is_running());
  3039. }
  3040. TEST(KeepAliveTest, ReadTimeout) {
  3041. Server svr;
  3042. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3043. std::this_thread::sleep_for(std::chrono::seconds(2));
  3044. res.set_content("a", "text/plain");
  3045. });
  3046. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3047. res.set_content("b", "text/plain");
  3048. });
  3049. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3050. while (!svr.is_running()) {
  3051. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3052. }
  3053. // Give GET time to get a few messages.
  3054. std::this_thread::sleep_for(std::chrono::seconds(1));
  3055. Client cli("localhost", PORT);
  3056. cli.set_keep_alive(true);
  3057. cli.set_read_timeout(std::chrono::seconds(1));
  3058. auto resa = cli.Get("/a");
  3059. ASSERT_TRUE(!resa);
  3060. EXPECT_EQ(Error::Read, resa.error());
  3061. auto resb = cli.Get("/b");
  3062. ASSERT_TRUE(resb);
  3063. EXPECT_EQ(200, resb->status);
  3064. EXPECT_EQ("b", resb->body);
  3065. svr.stop();
  3066. listen_thread.join();
  3067. ASSERT_FALSE(svr.is_running());
  3068. }
  3069. TEST(ClientProblemDetectionTest, ContentProvider) {
  3070. Server svr;
  3071. size_t content_length = 1024 * 1024;
  3072. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3073. res.set_content_provider(
  3074. content_length, "text/plain",
  3075. [&](size_t offset, size_t length, DataSink &sink) {
  3076. auto out_len = std::min(length, static_cast<size_t>(1024));
  3077. std::string out(out_len, '@');
  3078. sink.write(out.data(), out_len);
  3079. return offset < 4096;
  3080. },
  3081. [](bool success) { ASSERT_FALSE(success); });
  3082. });
  3083. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3084. while (!svr.is_running()) {
  3085. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3086. }
  3087. // Give GET time to get a few messages.
  3088. std::this_thread::sleep_for(std::chrono::seconds(1));
  3089. Client cli("localhost", PORT);
  3090. auto res = cli.Get("/hi", [&](const char * /*data*/, size_t /*data_length*/) {
  3091. return false;
  3092. });
  3093. ASSERT_FALSE(res);
  3094. svr.stop();
  3095. listen_thread.join();
  3096. ASSERT_FALSE(svr.is_running());
  3097. }
  3098. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  3099. Server svr;
  3100. svr.set_error_handler([](Request const &, Response &res) -> void {
  3101. res.set_chunked_content_provider(
  3102. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  3103. sink.os << "hello";
  3104. sink.os << "world";
  3105. sink.done();
  3106. return true;
  3107. });
  3108. });
  3109. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3110. while (!svr.is_running()) {
  3111. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3112. }
  3113. // Give GET time to get a few messages.
  3114. std::this_thread::sleep_for(std::chrono::seconds(1));
  3115. Client cli("localhost", PORT);
  3116. auto res = cli.Get("/");
  3117. ASSERT_TRUE(res);
  3118. EXPECT_EQ(404, res->status);
  3119. EXPECT_EQ("helloworld", res->body);
  3120. svr.stop();
  3121. listen_thread.join();
  3122. ASSERT_FALSE(svr.is_running());
  3123. }
  3124. TEST(GetWithParametersTest, GetWithParameters) {
  3125. Server svr;
  3126. svr.Get("/", [&](const Request &req, Response &res) {
  3127. auto text = req.get_param_value("hello");
  3128. res.set_content(text, "text/plain");
  3129. });
  3130. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3131. while (!svr.is_running()) {
  3132. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3133. }
  3134. std::this_thread::sleep_for(std::chrono::seconds(1));
  3135. Client cli("localhost", PORT);
  3136. Params params;
  3137. params.emplace("hello", "world");
  3138. auto res = cli.Get("/", params, Headers{});
  3139. ASSERT_TRUE(res);
  3140. EXPECT_EQ(200, res->status);
  3141. EXPECT_EQ("world", res->body);
  3142. svr.stop();
  3143. listen_thread.join();
  3144. ASSERT_FALSE(svr.is_running());
  3145. }
  3146. TEST(GetWithParametersTest, GetWithParameters2) {
  3147. Server svr;
  3148. svr.Get("/", [&](const Request &req, Response &res) {
  3149. auto text = req.get_param_value("hello");
  3150. res.set_content(text, "text/plain");
  3151. });
  3152. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3153. while (!svr.is_running()) {
  3154. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3155. }
  3156. std::this_thread::sleep_for(std::chrono::seconds(1));
  3157. Client cli("localhost", PORT);
  3158. Params params;
  3159. params.emplace("hello", "world");
  3160. std::string body;
  3161. auto res = cli.Get("/", params, Headers{},
  3162. [&](const char *data, size_t data_length) {
  3163. body.append(data, data_length);
  3164. return true;
  3165. });
  3166. ASSERT_TRUE(res);
  3167. EXPECT_EQ(200, res->status);
  3168. EXPECT_EQ("world", body);
  3169. svr.stop();
  3170. listen_thread.join();
  3171. ASSERT_FALSE(svr.is_running());
  3172. }
  3173. TEST(ClientDefaultHeadersTest, DefaultHeaders) {
  3174. Client cli("httpbin.org");
  3175. cli.set_default_headers({make_range_header({{1, 10}})});
  3176. cli.set_connection_timeout(5);
  3177. {
  3178. auto res = cli.Get("/range/32");
  3179. ASSERT_TRUE(res);
  3180. EXPECT_EQ("bcdefghijk", res->body);
  3181. EXPECT_EQ(206, res->status);
  3182. }
  3183. {
  3184. auto res = cli.Get("/range/32");
  3185. ASSERT_TRUE(res);
  3186. EXPECT_EQ("bcdefghijk", res->body);
  3187. EXPECT_EQ(206, res->status);
  3188. }
  3189. }
  3190. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  3191. Server svr;
  3192. svr.set_default_headers({{"Hello", "World"}});
  3193. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  3194. res.set_content("ok", "text/plain");
  3195. });
  3196. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3197. while (!svr.is_running()) {
  3198. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3199. }
  3200. std::this_thread::sleep_for(std::chrono::seconds(1));
  3201. Client cli("localhost", PORT);
  3202. auto res = cli.Get("/");
  3203. ASSERT_TRUE(res);
  3204. EXPECT_EQ(200, res->status);
  3205. EXPECT_EQ("ok", res->body);
  3206. EXPECT_EQ("World", res->get_header_value("Hello"));
  3207. svr.stop();
  3208. listen_thread.join();
  3209. ASSERT_FALSE(svr.is_running());
  3210. }
  3211. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3212. TEST(KeepAliveTest, ReadTimeoutSSL) {
  3213. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3214. ASSERT_TRUE(svr.is_valid());
  3215. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3216. std::this_thread::sleep_for(std::chrono::seconds(2));
  3217. res.set_content("a", "text/plain");
  3218. });
  3219. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3220. res.set_content("b", "text/plain");
  3221. });
  3222. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3223. while (!svr.is_running()) {
  3224. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3225. }
  3226. // Give GET time to get a few messages.
  3227. std::this_thread::sleep_for(std::chrono::seconds(1));
  3228. SSLClient cli("localhost", PORT);
  3229. cli.enable_server_certificate_verification(false);
  3230. cli.set_keep_alive(true);
  3231. cli.set_read_timeout(std::chrono::seconds(1));
  3232. auto resa = cli.Get("/a");
  3233. ASSERT_TRUE(!resa);
  3234. EXPECT_EQ(Error::Read, resa.error());
  3235. auto resb = cli.Get("/b");
  3236. ASSERT_TRUE(resb);
  3237. EXPECT_EQ(200, resb->status);
  3238. EXPECT_EQ("b", resb->body);
  3239. svr.stop();
  3240. listen_thread.join();
  3241. ASSERT_FALSE(svr.is_running());
  3242. }
  3243. #endif
  3244. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  3245. protected:
  3246. ServerTestWithAI_PASSIVE()
  3247. : cli_(HOST, PORT)
  3248. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3249. ,
  3250. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3251. #endif
  3252. {
  3253. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3254. cli_.enable_server_certificate_verification(false);
  3255. #endif
  3256. }
  3257. virtual void SetUp() {
  3258. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3259. res.set_content("Hello World!", "text/plain");
  3260. });
  3261. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(nullptr, PORT, AI_PASSIVE)); });
  3262. while (!svr_.is_running()) {
  3263. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3264. }
  3265. }
  3266. virtual void TearDown() {
  3267. svr_.stop();
  3268. t_.join();
  3269. }
  3270. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3271. SSLClient cli_;
  3272. SSLServer svr_;
  3273. #else
  3274. Client cli_;
  3275. Server svr_;
  3276. #endif
  3277. thread t_;
  3278. };
  3279. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  3280. auto res = cli_.Get("/hi");
  3281. ASSERT_TRUE(res);
  3282. EXPECT_EQ(200, res->status);
  3283. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3284. EXPECT_EQ("Hello World!", res->body);
  3285. }
  3286. class ServerUpDownTest : public ::testing::Test {
  3287. protected:
  3288. ServerUpDownTest() : cli_(HOST, PORT) {}
  3289. virtual void SetUp() {
  3290. t_ = thread([&]() {
  3291. svr_.bind_to_any_port(HOST);
  3292. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3293. ASSERT_TRUE(svr_.listen_after_bind());
  3294. });
  3295. while (!svr_.is_running()) {
  3296. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3297. }
  3298. }
  3299. virtual void TearDown() {
  3300. svr_.stop();
  3301. t_.join();
  3302. }
  3303. Client cli_;
  3304. Server svr_;
  3305. thread t_;
  3306. };
  3307. TEST_F(ServerUpDownTest, QuickStartStop) {
  3308. // Should not crash, especially when run with
  3309. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  3310. }
  3311. class PayloadMaxLengthTest : public ::testing::Test {
  3312. protected:
  3313. PayloadMaxLengthTest()
  3314. : cli_(HOST, PORT)
  3315. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3316. ,
  3317. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3318. #endif
  3319. {
  3320. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3321. cli_.enable_server_certificate_verification(false);
  3322. #endif
  3323. }
  3324. virtual void SetUp() {
  3325. svr_.set_payload_max_length(8);
  3326. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  3327. res.set_content("test", "text/plain");
  3328. });
  3329. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3330. while (!svr_.is_running()) {
  3331. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3332. }
  3333. }
  3334. virtual void TearDown() {
  3335. svr_.stop();
  3336. t_.join();
  3337. }
  3338. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3339. SSLClient cli_;
  3340. SSLServer svr_;
  3341. #else
  3342. Client cli_;
  3343. Server svr_;
  3344. #endif
  3345. thread t_;
  3346. };
  3347. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  3348. auto res = cli_.Post("/test", "123456789", "text/plain");
  3349. ASSERT_TRUE(res);
  3350. EXPECT_EQ(413, res->status);
  3351. res = cli_.Post("/test", "12345678", "text/plain");
  3352. ASSERT_TRUE(res);
  3353. EXPECT_EQ(200, res->status);
  3354. }
  3355. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3356. TEST(SSLClientTest, UpdateCAStore) {
  3357. httplib::SSLClient httplib_client("www.google.com");
  3358. auto ca_store_1 = X509_STORE_new();
  3359. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  3360. nullptr);
  3361. httplib_client.set_ca_cert_store(ca_store_1);
  3362. auto ca_store_2 = X509_STORE_new();
  3363. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  3364. nullptr);
  3365. httplib_client.set_ca_cert_store(ca_store_2);
  3366. }
  3367. TEST(SSLClientTest, ServerNameIndication) {
  3368. SSLClient cli("httpbin.org", 443);
  3369. auto res = cli.Get("/get");
  3370. ASSERT_TRUE(res);
  3371. ASSERT_EQ(200, res->status);
  3372. }
  3373. TEST(SSLClientTest, ServerCertificateVerification1) {
  3374. SSLClient cli("google.com");
  3375. auto res = cli.Get("/");
  3376. ASSERT_TRUE(res);
  3377. ASSERT_EQ(301, res->status);
  3378. }
  3379. TEST(SSLClientTest, ServerCertificateVerification2) {
  3380. SSLClient cli("google.com");
  3381. cli.enable_server_certificate_verification(true);
  3382. cli.set_ca_cert_path("hello");
  3383. auto res = cli.Get("/");
  3384. ASSERT_TRUE(!res);
  3385. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  3386. }
  3387. TEST(SSLClientTest, ServerCertificateVerification3) {
  3388. SSLClient cli("google.com");
  3389. cli.set_ca_cert_path(CA_CERT_FILE);
  3390. auto res = cli.Get("/");
  3391. ASSERT_TRUE(res);
  3392. ASSERT_EQ(301, res->status);
  3393. }
  3394. TEST(SSLClientTest, ServerCertificateVerification4) {
  3395. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  3396. ASSERT_TRUE(svr.is_valid());
  3397. svr.Get("/test", [&](const Request &, Response &res) {
  3398. res.set_content("test", "text/plain");
  3399. svr.stop();
  3400. ASSERT_TRUE(true);
  3401. });
  3402. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  3403. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3404. SSLClient cli("127.0.0.1", PORT);
  3405. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  3406. cli.enable_server_certificate_verification(true);
  3407. cli.set_connection_timeout(30);
  3408. auto res = cli.Get("/test");
  3409. ASSERT_TRUE(res);
  3410. ASSERT_EQ(200, res->status);
  3411. t.join();
  3412. }
  3413. TEST(SSLClientTest, WildcardHostNameMatch) {
  3414. SSLClient cli("www.youtube.com");
  3415. cli.set_ca_cert_path(CA_CERT_FILE);
  3416. cli.enable_server_certificate_verification(true);
  3417. cli.set_follow_location(true);
  3418. auto res = cli.Get("/");
  3419. ASSERT_TRUE(res);
  3420. ASSERT_EQ(200, res->status);
  3421. }
  3422. TEST(SSLClientServerTest, ClientCertPresent) {
  3423. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3424. CLIENT_CA_CERT_DIR);
  3425. ASSERT_TRUE(svr.is_valid());
  3426. svr.Get("/test", [&](const Request &req, Response &res) {
  3427. res.set_content("test", "text/plain");
  3428. svr.stop();
  3429. ASSERT_TRUE(true);
  3430. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3431. ASSERT_TRUE(peer_cert != nullptr);
  3432. auto subject_name = X509_get_subject_name(peer_cert);
  3433. ASSERT_TRUE(subject_name != nullptr);
  3434. std::string common_name;
  3435. {
  3436. char name[BUFSIZ];
  3437. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3438. name, sizeof(name));
  3439. common_name.assign(name, static_cast<size_t>(name_len));
  3440. }
  3441. EXPECT_EQ("Common Name", common_name);
  3442. X509_free(peer_cert);
  3443. });
  3444. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3445. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3446. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3447. cli.enable_server_certificate_verification(false);
  3448. cli.set_connection_timeout(30);
  3449. auto res = cli.Get("/test");
  3450. ASSERT_TRUE(res);
  3451. ASSERT_EQ(200, res->status);
  3452. t.join();
  3453. }
  3454. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  3455. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  3456. X509 *server_cert;
  3457. EVP_PKEY *server_private_key;
  3458. X509_STORE *client_ca_cert_store;
  3459. X509 *client_cert;
  3460. EVP_PKEY *client_private_key;
  3461. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  3462. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3463. fclose(f);
  3464. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  3465. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  3466. fclose(f);
  3467. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  3468. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3469. client_ca_cert_store = X509_STORE_new();
  3470. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  3471. X509_free(client_cert);
  3472. fclose(f);
  3473. f = fopen(CLIENT_CERT_FILE, "r+");
  3474. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3475. fclose(f);
  3476. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  3477. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  3478. fclose(f);
  3479. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  3480. ASSERT_TRUE(svr.is_valid());
  3481. svr.Get("/test", [&](const Request &req, Response &res) {
  3482. res.set_content("test", "text/plain");
  3483. svr.stop();
  3484. ASSERT_TRUE(true);
  3485. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3486. ASSERT_TRUE(peer_cert != nullptr);
  3487. auto subject_name = X509_get_subject_name(peer_cert);
  3488. ASSERT_TRUE(subject_name != nullptr);
  3489. std::string common_name;
  3490. {
  3491. char name[BUFSIZ];
  3492. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3493. name, sizeof(name));
  3494. common_name.assign(name, static_cast<size_t>(name_len));
  3495. }
  3496. EXPECT_EQ("Common Name", common_name);
  3497. X509_free(peer_cert);
  3498. });
  3499. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3500. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3501. SSLClient cli(HOST, PORT, client_cert, client_private_key);
  3502. cli.enable_server_certificate_verification(false);
  3503. cli.set_connection_timeout(30);
  3504. auto res = cli.Get("/test");
  3505. ASSERT_TRUE(res);
  3506. ASSERT_EQ(200, res->status);
  3507. X509_free(server_cert);
  3508. EVP_PKEY_free(server_private_key);
  3509. X509_free(client_cert);
  3510. EVP_PKEY_free(client_private_key);
  3511. t.join();
  3512. }
  3513. #endif
  3514. TEST(SSLClientServerTest, ClientCertMissing) {
  3515. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3516. CLIENT_CA_CERT_DIR);
  3517. ASSERT_TRUE(svr.is_valid());
  3518. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  3519. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3520. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3521. SSLClient cli(HOST, PORT);
  3522. auto res = cli.Get("/test");
  3523. cli.set_connection_timeout(30);
  3524. ASSERT_TRUE(!res);
  3525. EXPECT_EQ(Error::SSLServerVerification, res.error());
  3526. svr.stop();
  3527. t.join();
  3528. }
  3529. TEST(SSLClientServerTest, TrustDirOptional) {
  3530. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3531. ASSERT_TRUE(svr.is_valid());
  3532. svr.Get("/test", [&](const Request &, Response &res) {
  3533. res.set_content("test", "text/plain");
  3534. svr.stop();
  3535. });
  3536. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3537. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3538. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3539. cli.enable_server_certificate_verification(false);
  3540. cli.set_connection_timeout(30);
  3541. auto res = cli.Get("/test");
  3542. ASSERT_TRUE(res);
  3543. ASSERT_EQ(200, res->status);
  3544. t.join();
  3545. }
  3546. TEST(SSLClientServerTest, SSLConnectTimeout) {
  3547. class NoListenSSLServer : public SSLServer {
  3548. public:
  3549. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  3550. const char *client_ca_cert_file_path,
  3551. const char *client_ca_cert_dir_path = nullptr)
  3552. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  3553. client_ca_cert_dir_path),
  3554. stop_(false) {}
  3555. bool stop_;
  3556. private:
  3557. bool process_and_close_socket(socket_t /*sock*/) override {
  3558. // Don't create SSL context
  3559. while (!stop_) {
  3560. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3561. }
  3562. return true;
  3563. }
  3564. };
  3565. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  3566. CLIENT_CA_CERT_FILE);
  3567. ASSERT_TRUE(svr.is_valid());
  3568. svr.Get("/test", [&](const Request &, Response &res) {
  3569. res.set_content("test", "text/plain");
  3570. });
  3571. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3572. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3573. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3574. cli.enable_server_certificate_verification(false);
  3575. cli.set_connection_timeout(1);
  3576. auto res = cli.Get("/test");
  3577. ASSERT_TRUE(!res);
  3578. EXPECT_EQ(Error::SSLConnection, res.error());
  3579. svr.stop_ = true;
  3580. svr.stop();
  3581. t.join();
  3582. }
  3583. #endif
  3584. #ifdef _WIN32
  3585. TEST(CleanupTest, WSACleanup) {
  3586. int ret = WSACleanup();
  3587. ASSERT_EQ(0, ret);
  3588. }
  3589. #endif
  3590. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  3591. TEST(NoSSLSupport, SimpleInterface) {
  3592. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  3593. }
  3594. #endif
  3595. TEST(InvalidScheme, SimpleInterface) {
  3596. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  3597. }
  3598. TEST(NoScheme, SimpleInterface) {
  3599. Client cli("yahoo.com:80");
  3600. ASSERT_TRUE(cli.is_valid());
  3601. }
  3602. TEST(SendAPI, SimpleInterface) {
  3603. Client cli("http://yahoo.com");
  3604. Request req;
  3605. req.method = "GET";
  3606. req.path = "/";
  3607. auto res = cli.send(req);
  3608. ASSERT_TRUE(res);
  3609. EXPECT_EQ(301, res->status);
  3610. }
  3611. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3612. TEST(YahooRedirectTest2, SimpleInterface) {
  3613. Client cli("http://yahoo.com");
  3614. auto res = cli.Get("/");
  3615. ASSERT_TRUE(res);
  3616. EXPECT_EQ(301, res->status);
  3617. cli.set_follow_location(true);
  3618. res = cli.Get("/");
  3619. ASSERT_TRUE(res);
  3620. EXPECT_EQ(200, res->status);
  3621. EXPECT_EQ("https://yahoo.com/", res->location);
  3622. }
  3623. TEST(YahooRedirectTest3, SimpleInterface) {
  3624. Client cli("https://yahoo.com");
  3625. auto res = cli.Get("/");
  3626. ASSERT_TRUE(res);
  3627. EXPECT_EQ(301, res->status);
  3628. cli.set_follow_location(true);
  3629. res = cli.Get("/");
  3630. ASSERT_TRUE(res);
  3631. EXPECT_EQ(200, res->status);
  3632. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3633. }
  3634. TEST(YahooRedirectTest3, NewResultInterface) {
  3635. Client cli("https://yahoo.com");
  3636. auto res = cli.Get("/");
  3637. ASSERT_TRUE(res);
  3638. ASSERT_FALSE(!res);
  3639. ASSERT_TRUE(res);
  3640. ASSERT_FALSE(res == nullptr);
  3641. ASSERT_TRUE(res != nullptr);
  3642. EXPECT_EQ(Error::Success, res.error());
  3643. EXPECT_EQ(301, res.value().status);
  3644. EXPECT_EQ(301, (*res).status);
  3645. EXPECT_EQ(301, res->status);
  3646. cli.set_follow_location(true);
  3647. res = cli.Get("/");
  3648. ASSERT_TRUE(res);
  3649. EXPECT_EQ(Error::Success, res.error());
  3650. EXPECT_EQ(200, res.value().status);
  3651. EXPECT_EQ(200, (*res).status);
  3652. EXPECT_EQ(200, res->status);
  3653. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3654. }
  3655. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3656. TEST(DecodeWithChunkedEncoding, BrotliEncoding) {
  3657. Client cli("https://cdnjs.cloudflare.com");
  3658. auto res =
  3659. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  3660. ASSERT_TRUE(res);
  3661. EXPECT_EQ(200, res->status);
  3662. EXPECT_EQ(287630, res->body.size());
  3663. EXPECT_EQ("application/javascript; charset=utf-8",
  3664. res->get_header_value("Content-Type"));
  3665. }
  3666. #endif
  3667. TEST(HttpsToHttpRedirectTest, SimpleInterface) {
  3668. Client cli("https://nghttp2.org");
  3669. cli.set_follow_location(true);
  3670. auto res =
  3671. cli.Get("/httpbin/"
  3672. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  3673. ASSERT_TRUE(res);
  3674. EXPECT_EQ(200, res->status);
  3675. }
  3676. TEST(HttpsToHttpRedirectTest2, SimpleInterface) {
  3677. Client cli("https://nghttp2.org");
  3678. cli.set_follow_location(true);
  3679. Params params;
  3680. params.emplace("url", "http://www.google.com");
  3681. params.emplace("status_code", "302");
  3682. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  3683. ASSERT_TRUE(res);
  3684. EXPECT_EQ(200, res->status);
  3685. }
  3686. TEST(HttpsToHttpRedirectTest3, SimpleInterface) {
  3687. Client cli("https://nghttp2.org");
  3688. cli.set_follow_location(true);
  3689. Params params;
  3690. params.emplace("url", "http://www.google.com");
  3691. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  3692. ASSERT_TRUE(res);
  3693. EXPECT_EQ(200, res->status);
  3694. }
  3695. #endif