/
2Rook-packageRhttpd-class.........................................15Rh 2Rook-packageRhttpd-class.........................................15Rh

2Rook-packageRhttpd-class.........................................15Rh - PDF document

cheryl-pisano
cheryl-pisano . @cheryl-pisano
Follow
364 views
Uploaded On 2015-10-14

2Rook-packageRhttpd-class.........................................15Rh - PPT Presentation

RookpackageRookAwebserverinterfaceandpackageforR DescriptionThishelppagedenestheRookspecicationItborrowsheavilyfromRubysRackprojecthttprackrubyforgeorgAfterreadingthisdocumentreadtheRht ID: 160132

Rook-packageRook:AwebserverinterfaceandpackageforR DescriptionThishelppagedenestheRookspecication.ItborrowsheavilyfromRuby'sRackproject:http://rack.rubyforge.org/.Afterreadingthisdocument readtheRht

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "2Rook-packageRhttpd-class.................." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

Package`Rook'August29,2016TypePackageTitleRook-awebserverinterfaceforRVersion1.1-1Date2014-10-20AuthorJeffreyHorner&#xjeff;&#xrey.;&#xhorn;r@g;&#xmail;&#x.com;MaintainerJeffreyHorner&#xjeff;&#xrey.;&#xhorn;r@g;&#xmail;&#x.com;DescriptionThispackagecontainstheRookspecicationandconveniencesoftwareforbuildingandrunningRookapplications.Togetstarted,besureandreadtheRookhelplerst.DependsR&#xjeff;&#xrey.;&#xhorn;r@g;&#xmail;&#x.com;(=2.13.0)Importsutils,tools,methods,brewLicenseGPL-2LazyLoadyesNeedsCompilationyesRepositoryCRANDate/Publication2014-10-2019:18:06Rtopicsdocumented:Rook-package........................................2App-class..........................................4Brewery-class........................................5Builder-class........................................6File-class..........................................7is_rookable.........................................8Middleware-class......................................8Mime-class.........................................9Multipart-class.......................................10Redirect-class........................................11Request-class........................................11Response-class.......................................141 2Rook-packageRhttpd-class.........................................15RhttpdApp-class......................................17RhttpdErrorStream-class..................................18RhttpdInputStream-class..................................18Server............................................19Static-class.........................................19suspend_console......................................19URLMap-class.......................................20Utils-class..........................................21Index23 Rook-packageRook:AwebserverinterfaceandpackageforR DescriptionThishelppagedenestheRookspecication.ItborrowsheavilyfromRuby'sRackproject:http://rack.rubyforge.org/.Afterreadingthisdocument,readtheRhttpdhelpleasitwillgetyoufamiliarwithinstallingandrunningRookapplications.Thenexploretheexampleapplicationslocatedin:system.file('exampleApps',package='Rook').RookapplicationsARookapplicationisanRreferenceclassobjectthatimplementsa'call'methodoranRclosurethattakesexactlyoneargument,anenvironment,andreturnsalistwiththreenamedelements:'status','headers',and'body'.HelloWorldHereisabasicRookapplicationasaclosurethatimplements'helloworld':function(env){body=paste('&#xh100;World!ThisisRook',env$rook.version,'&#x/h10;.')list(status=200L,headers=list('Content-Type'='text/html'),body=body)}Andtheequivalentreferenceclassexample: Rook-package3setRefClass('HelloWorld',methods=list(call=function(env){list(status=200L,headers=list('Content-Type'='text/html'),body=paste('&#xh100;World!ThisisRook',env$rook.version,'&#x/h10;.'))}))TheEnvironmentTheenvironmentargumentisatrueRenvironmentobjectwhichtheapplicationisfreetomodify.Itisrequiredtocontainthefollowingvariables:REQUEST_METHODTheHTTPrequestmethod,suchas"GET"or"POST".Thiscannoteverbeanemptystring,andsoisalwaysrequired.SCRIPT_NAMETheinitialportionoftherequestURL's"path"thatcorrespondstotheapplica-tionobject,sothattheapplicationknowsitsvirtual"location".Thismaybeanemptystring,iftheapplicationcorrespondstothe"root"oftheserver.PATH_INFOTheremainderoftherequestURL's"path",designatingthevirtual"location"oftherequest'stargetwithintheapplication.Thismaybeanemptystring,iftherequestURLtargetstheapplicationrootanddoesnothaveatrailingslash.Thisvaluemaybepercent-encodedwhenIoriginatingfromaURL.QUERY_STRINGTheportionoftherequestURLthatfollowsthe?,ifany.Maybeempty,butisalwaysrequired!SERVER_NAME,SERVER_PORTWhencombinedwithSCRIPT_NAMEandPATH_INFO,thesevariablescanbeusedtocompletetheURL.NotehoweverthatHTTP_HOST,ifpresent,shouldbeusedinpreferencetoSERVER_NAMEforreconstructingtherequestURL.SERVER_NAMEandSERVER_PORTcanneverbeemptystrings,andsoarealwaysrequired.HTTP_VariablesVariablescorrespondingtotheclient-suppliedHTTPrequestheaders(i.e.,vari-ableswhosenamesbeginwithHTTP_).ThepresenceorabsenceofthesevariablesshouldcorrespondwiththepresenceorabsenceoftheappropriateHTTPheaderintherequest.Inaddition,theenvironmentmustincludethefollowingRook-specicvariables:rook.versionThisversionofRook.rook.url_scheme'http'or'https',dependingontherequestURL.rook.inputSee“TheInputStream”section.rook.errorsSee“TheErrorStream”section. 4App-classTheInputStreamTherook.inputvariablemustcontainanobjectcreatedfromareferenceclassthatimplementsread_lines(),read(),andrewind():read_lines(l=-1L):takesoneargument,thenumberoflinestoread.Includespartialendingline.read(l=-1L):takesoneargument,thenumberofbytestoread.Returnsarawvector.rewind():Rewindstheinputstreambacktothebeginning.TheErrorStreamTherook.errorvariablemustcontainanobjectcreatedfromareferenceclassthatimplementsflush()andcat():flush():calledwithnoargumentsandmakestheerrorstreamimmediatelyappear.cat(...,sep="",fill=FALSE,labels=NULL):calledwiththesameargumentsasR's"cat"withoutthefileandappendargument.TheResponseRookapplicationsreturnalistwiththreenamedelements:'status','headers',and'body'.'status':AnHTTPstatusvalueasintegerandmustbegreaterthanorequalto100.'headers':AnamedlistthatcontainsonlycharactervaluescorrespondingtovalidHTTPheaders.'body':Eitheracharacterorrawvector.Ifthecharactervectorisnamedwithvalue'file'thenvalueofthevectorisinterpretedasthelocationofale.Author(s)JeffreyHornerfrey&#xjef2;倀.horner@gmail.com App-classClassApp DescriptionAbstractclassfromwhichMiddlewareandBuilderinherit.Providestheappeld.Appcanalsobeusedtoinstantiatereferenceclassedapplicationswrappedaroundafunction.SeeMiddlewareforanexample.Fieldsapp:ARookapplication. Brewery-class5Methodsnew(app=NULL):CreatesanewAppobject.appisanyRookawareRobject.SeeAlsois_rookable,Builder,andMiddleware. Brewery-classClassBrewery DescriptionAMiddlewareclassformappingURLstoadirectoryoflesthataresubsequentlypassedtobrew.Whenaleisbrewed,thetwovariablesreq(anobjectofclassRequest)andres(anobjectofclassResponse)areavailableforuse.Methodsnew(url,root,...):urlisacharacterstringorregexponwhichtomatch,rootisthenameofthedirectorywherebrewlesreside.Namedargumentscanbepassedinvia...andwillbeavailablewithinthescopeofeachbrewedle.SeeAlsoRhttpd,Builder,Redirect,andbrew.Examples##Thisapplicationrunsanyfilefoundintempdir()throughbrew.#sRhttpd$new()##Notrun:s$start(quiet=TRUE)##End(Notrun)&#xh100;cat("Number:&#x%=rn;&#xorm1;&#x%000;&#x/h10;()file=file.path(tempdir(),"index.html"))s$add(name="random",app=Builder$new(Brewery$new(url="/",root=tempdir()),Redirect$new("/index.html")))##Notrun:s$browse('random')#Opensabrowserwindowtotheapp.##End(Notrun) 6Builder-classfile.remove(file.path(tempdir(),"index.html"))s$remove(all=TRUE)rm(s) Builder-classClassBuilder DescriptionAconvenienceobjectforcombiningvariousMiddlewarewithadefaultapplicationtocreateamorecomplexRookapplication.Methodsnew(...):ArgumentscanbeanyMiddlewareobjectwhilethelastargumentinthelistmustbeavalidRookapplication.Thatis,itwillhandletheincomingrequestwithoutdeferringtoanotherapplication.SeeAlsoRhttpd,Static,Brewery,andRedirect.Examples#ThefollowingistheHmiscexample.Explorethefolder#system.file('exampleApps/Hmisc',package='Rook')formoreinformation.sRhttpd$new()##Notrun:library(Hmisc)dir.create(file.path(tempdir(),'plots'),showWarnings=FALSE)s$add(name="Hmisc",app=Builder$new(Static$new(urls=c('/css','/images','/javascript'),root=system.file('exampleApps/Hmisc',package='Rook')),Static$new(urls='/plots',root=tempdir()),Brewery$new(url='/brew',root=system.file('exampleApps/Hmisc',package='Rook'),imagepath=file.path(tempdir(),'plots'),imageurl='../plots/'),Redirect$new('/brew/useR2007.rhtml')))s$start(quiet=TRUE)s$browse('Hmisc')#Opensabrowserwindowtotheapplication.s$remove(all=TRUE) File-class7s$stop()##End(Notrun) File-classClassFile DescriptionARookapplicationthatservesstaticlesfromarootdirectory,accordingtothepathinfooftheRookrequest.Methodsnew(root):rootisthenameofthedirectoryfromwheretoserveles.SeeAlsoRhttpd.Examples#Thisexampleservesallyourfilesin/etc(onUNIXandMaconly).##Notethatwhenyouopentheapplication,youwillseetheword#'Forbidden'."File"doesn'tservedirectories,soyoumustamendthe#urlinthelocationbarwiththefileyouwanttoview.Tryadding/passwd.sRhttpd$new()##Notrun:s$start(quiet=TRUE)##End(Notrun)s$add(name="etc",app=File$new('/etc'))##Notrun:s$browse('etc')#Opensabrowserwindowtotheapp.##End(Notrun)s$remove(all=TRUE)rm(s) 8Middleware-class is_rookableTestforRookableapplications DescriptionAconveniencefunctionfortestingwhetherornotobjectsareeitherafunctionorreferenceclassasdenedbytheRookspecicationforapplications.Usageis_rookable(app)ArgumentsappAnyRobject.ValueLogicaldeterminingwhetherornotargumentisRookable.Notvectorized.SeeAlsoRook. Middleware-classClassMiddleware DescriptionAnabstractclassforbuildingRookMiddlewareapplications.Middlewareapplicationseitherhan-dletheincomingwebrequestorhandofftherequesttotheRookappdenedintheeldofthesamename.Methodsset_app(app):appisaRookapplicationthatwillhandletherequestifthisMiddlewareappdoesnot.SeeAlsoThefollowingclassesimplementMiddleware:BreweryandStatic. Mime-class9Examples#Middlewareapplicationsaretypicallyinstantiatedintheargumentlistof#Builder$new(),buthereisstand-aloneexample.##Onceyourbrowserloadstheapp,youwillseesomethinglikethisin#yourlocationbar:http://127.0.0.1:28649/custom/middle.Add'/foo'#ontotheendofthatandreload.setRefClass('FooBar',contains='Middleware',methods=list(initialize=function(...){#apptodeferto.callSuper(app=App$new(function(env){resResponse$new()&#xh100;res$write("'mthedeferred&#x/h10;app.)res$finish()}))},call=function(env){reqRequest$new(env)resResponse$new()if(length(grep('foo',req$path_info()))){&#xh100;res$write("'mthemiddleware&#x/h10;app.)return(res$finish())}else{app$call(env)}}))sRhttpd$new()##Notrun:s$start(quiet=TRUE)##End(Notrun)s$add(name="middle",app=getRefClass('FooBar')$new())##Notrun:s$browse('middle')#Opensabrowserwindowtotheapp.##End(Notrun)s$remove(all=TRUE)rm(s) Mime-classClassMimeandobjectMime DescriptionAconvenienceobjectfordeterminingtheMIMEtypeofalename. 10Multipart-classMethodsfile_extname(fname=NULL):Returnstheleextensionsforthegivenle.mime_type(ext=NULL,fallback='application/octet-stream'):ReturnstheMIMEtypegiventheleextension.Besuretoincludethedotcharacterinext.Ifnomatchisfound,thenthefallbackMIMEtypeisreturned.ExamplesMime$file_extname('foo.png')Mime$mime_type('.png') Multipart-classClassMultipartandobjectMultipart DescriptionAconvenienceobjectforparsingmultipart/form-dataPOSTpayloads.Methodsparse(env):ReturnsparsedPOSTpayloadasanamedlist.envisanenvironmentcreatedbyRhttpdandconformstotheRookspecication.SeeAlsoRhttpd,Request,andResponse.ExamplessRhttpd$new()##Notrun:s$start(quiet=TRUE)##End(Notrun)s$add(name="multi",app=function(env){reqRequest$new(env)resResponse$new()res$write('enctype="multipart/form-data"orm;&#x-500;method=POST')res$write('Uploadafile:type=file&#xinpu;&#xt-50;�name=fileUpload')res$write('&#xinpu;&#xt-50;�&#x/for;&#xm000; r00;type=submit')postMultipart$parse(env)if(length(post)){poststrpaste(capture.output(str(post),file=NULL),collapse='\n')res$write(c('&#xpre0;',poststr,'&#x/pre;'))}res$finish()}) Redirect-class11##Notrun:s$browse('multi')#Opensabrowserwindowtotheapp.##End(Notrun)s$remove(all=TRUE)rm(s) Redirect-classClassRedirect DescriptionARookapplicationwhoseonlyroleistoreturnanHTTPredirectheadertothegivenurl.Methodsnew(url):ReturnsaRookobject.urlisacharacterstringwhosevalueisafullorrelativeurltowhichthebrowserisredirected.SeeAlsoSeeBreweryforanexample. Request-classClassRequest DescriptionAconvenienceclassforworkingwithaRookenvironment.Besuretoseetheexampleattheendofthishelple.Methodsparseable_data():ReturnsabooleanvaluedeterminingifthePOSTpayloadisparseable.url():Returnsurlasacharacterstringcontainingthescheme,host,port,andpossiblytheGETquerystringifsupplied.request_method():ReturnstheHTTPmethodasacharacterstring,e.g.'GET','POST',etc.GET():Returnsanamedlistcontainingthevariablesparsedfromthequerystring.post():ReturnsTRUEifthecurrentrequestmethodis'POST',FALSEotherwise.new(env):InstantiatesanewRequestobjectforthegivenRookenvironment.media_type():Returnsthemediatypeforthecurrentrequestasacharacterstring.query_string():Returnstheunparsedquerystring.fullpath():Returnsthesamestringasurl()butwithoutthescheme,host,andport. 12Request-classreferer()orreferrer():Returnsthereferringurl.cookies():Returnsanycookiesintherequestasanamedlist.content_charset():Returnsthecontentcharsetasacharacterstring.head():ReturnsTRUEiftheHTTPmethodis'HEAD',FALSEotherwise.accept_encoding():Returnstheacceptencodingheaderasacharacterstring.content_length():Returnscontentlengthheadervalueasastring.form_data():ReturnsTRUEifthere'sformdata,e.g.POSTdatawiththerequest,FALSEother-wise.xhr():Returnsthex-requested-withheadervalueasacharacterstring.params():ReturnsthecombinationofPOST()andGET()inonenamedlist.media_type_params():Returnsanymediatypeparametersfromthecontenttypeasanamedlist.user_agent():Returnstheuser-agentheadervalueasacharacterstring.put():ReturnsTRUEifthecurrentrequestisa'PUT'.get():ReturnsTRUEifthecurrentrequestisa'GET'.path():Returnsacharacterstringlikefullpath()butwithoutthequerystring.body():Returnsthe'rook.input'objectfromtheenvironment.SeeRhttpdInputStreamformoreinformation.port():Returnstheserverportasaninteger.ehost_with_port():Returnsthehostandportasacharacterstringseparatedby':'.scheme():Returnsthescheme,e.g.'http'or'https',asacharacterstring.ip():ReturnstheremoteIPaddressasacharacterstring.options():ReturnsTRUEifthecurrentrequestis'OPTIONS'.to_url(url,...):Concatenatesthescriptnamewiththeurlargumentalongwithanynamedparameterspassedvia....host():Returnstheserverhostasacharacterstring.POST():ReturnsanamedlistcontainingthevariablesparsedfromthePOSTpayload.trace():ReturnsTRUEifthecurrentrequestis'TRACE'.script_name(s=NULL):Returnsthescriptnameoftheapplication,e.g.'/custom/multi'.Also,ifsisnotNULL,setsthescriptnametos.content_type():Returnsthecontent-typeheadervalueasacharacterstring.delete():ReturnsTRUEifthecurrentrequestis'DELETE'.path_info(s=NULL):Returnstheportionoftheurlafterthescriptnameasacharacterstring.IfsisnotNULL,setsthepathinfotos.SeeAlsoRhttpdandResponse. Request-class13Examples##Thefollowingexampleprintsouttheresultofeachmethod.#ls_strfunction(s)paste(capture.output(str(s),file=NULL),collapse='\n')sRhttpd$new()##Notrun:s$start(quiet=TRUE)##End(Notrun)s$add(name="request",app=function(env){reqRequest$new(env)resResponse$new()res$set_cookie('imacookie','42')actionreq$to_url('/foo',bar=1,baz='three')res$write('enctype="multipart/form-data"method=POSTaction="')res$write(action)res$write('orm;&#x-500;"')res$write('Uploadafile:type=file&#xinpu;&#xt-50;�name=fileUpload')res$write('&#xinpu;&#xt-50;�&#x/for;&#xm000; r00;&#xpre0;type=submit')res$write(c('parseable_data:',req$parseable_data(),'\n'))res$write(c('url:',req$url(),'\n'))res$write(c('request_method:',req$request_method(),'\n'))res$write(c('GET:',ls_str(req$GET()),'\n'))res$write(c('post:',req$post(),'\n'))res$write(c('media_type:',req$media_type(),'\n'))res$write(c('query_string:',req$query_string(),'\n'))res$write(c('fullpath:',req$fullpath(),'\n'))res$write(c('referer:',req$referer(),'\n'))res$write(c('cookies:',ls_str(req$cookies()),'\n'))res$write(c('content_charset:',req$content_charset(),'\n'))res$write(c('head:',req$head(),'\n'))res$write(c('accept_encoding:',req$accept_encoding(),'\n'))res$write(c('content_length:',req$content_length(),'\n'))res$write(c('form_data:',req$form_data(),'\n'))res$write(c('xhr:',req$xhr(),'\n'))res$write(c('params:',ls_str(req$params()),'\n'))res$write(c('media_type_params:\n',ls_str(req$media_type_params()),'\n'))res$write(c('user_agent:',req$user_agent(),'\n'))res$write(c('put:',req$put(),'\n'))res$write(c('get:',req$get(),'\n'))res$write(c('path:',req$path(),'\n'))res$write(c('body:',ls_str(req$body()),'\n'))res$write(c('port:',req$port(),'\n'))res$write(c('host_with_port:',req$host_with_port(),'\n'))res$write(c('scheme:',req$scheme(),'\n'))res$write(c('ip:',req$ip(),'\n'))res$write(c('options:',req$options(),'\n'))res$write(c('to_url:',req$to_url('foo',bar=1,baz='two'),'\n'))res$write(c('host:',req$host(),'\n'))res$write(c('POST:',ls_str(req$POST()),'\n')) 14Response-classres$write(c('trace:',req$trace(),'\n'))res$write(c('script_name:',req$script_name(),'\n'))res$write(c('content_type:',req$content_type(),'\n'))res$write(c('delete:',req$delete(),'\n'))res$write(c('path_info:',req$path_info(),'\n'))res$write(c('\nRacenv:',ls_str(as.list(env)),'\n'))res$finish()})##Notrun:s$browse('request')#Opensabrowserwindowtotheapp.##End(Notrun)s$remove(all=TRUE)rm(s) Response-classClassResponse DescriptionAconvenienceclassforcreatingRookresponses.Methodsheader(key,value):SetsanHTTPheaderfortheresponse.Bothkeyandvaluemustbechar-acterstrings.Ifvalueismissing,thentheheadervalueisreturned.redirect(target,status=302):SetsupanHTTPredirecttothetargeturl.write(str):Takesacharactervectorandappendsittotheresponsebody.new(body='',status=200,headers=list()):CreateanewResponseobject.bodyisachar-actervector,statusisanHTTPstatusvalue.headersisanamedlist.set_cookie(key,value):SetsanHTTPcookiefortheresponse.Bothkeyandvaluemustbecharacterstrings.delete_cookie(key,value):SendsappropriateHTTPheadertodeletetheassociatedcookieontheclient.keyandvaluemustbecharacterstrings.finish():ReturnstheresponseaccordingtotheRookspecication.SeeAlsoRhttpdandRequest. Rhttpd-class15ExamplessRhttpd$new()##Notrun:s$start(quiet=TRUE)##End(Notrun)s$add(name="response",app=function(env){reqRequest$new(env)resResponse$new()res$write('hello')res$finish()})##Notrun:s$browse('response')#Opensabrowserwindowtotheapp.##End(Notrun)s$remove(all=TRUE)rm(s) Rhttpd-classClassRhttpd DescriptionRhttpdisaconvenienceclassforinstallingandrunningRookapplications.IthidesthedetailsofstartingandstoppingtheserverandaddingandremovingRookapplicationsfromtheserver.UsersstartsbycreatingoneRhttpdobject,thenaddingapplicationstoit,andthenstartingtheserver(seethesection“Examples”foratypicalsession).Therearenorestrictionsoncreatingmorethanoneserverobject,butknowthatitonlymanagestheapplicationsthatareaddedtoitandnotothers.Applicationscanbeaddedandremovedregardlessofwhetherornottheserverisrunning.Stoppingtheserverdoesnotremoveanyapplications.Addinganapplicationwiththesamenameasonealreadyinstalledsimplyoverwritestheoneinstalled.Iftheserverisstartedwithnoapplicationsinstalled,itwillinstalltheapplicationnamedRookTestApplocatedin:system.file('exampleApps/RookTestApp.R',package='Rook').Also,seebrowseURLtolearnhowtogetRtoautomaticallylaunchyourfavoritewebbrowser.NOTE:ThisversionofRookcanonlylistenontheloopbackdevice.Methodsopen(x)orbrowse(x):CallsbrowseURLontheinstalledRookapplicationdesignatedbyx.xiseitheranintegeroracharacterstring.Seetheoutputofprint().print()orshow():ListstheinstalledRookapplications. 16Rhttpd-classremove(app,all=FALSE):Removestheapplicationknowntotheserver.appcanbeanRhttpdAppobjectpreviouslyadded,thenameoftheapplicationasacharacterstring,oranindexasanumericorintegervalue.Seetheoutputofprint().full_url(i):Returnstheabsoluteurltotheapplicationforthegivenindex.start(listen='127.0.0.1',port=getOption('help.ports'),quiet=FALSE):Startstheserverontheloopbackdeviceandport.listenisalwayscharacterstring.Notethatiftherearenoapplicationsaddedtotheobjectpriortostarting,thentheRookTestApplocatedinsystem.file('exampleApps/RookTestApp.R',package='Rook')isautomaticallyadded.new():CreateanewRhttpdobject.launch(...):Combinesthestepsofstartingtheserver,creatinganRhttpdAppobject,addingittotheserver,andopeningtheappinthebrowser....argumentispassedtoRhttpdApp$new().debug():ReturnstheintegervalueprovidedbygetOption('Rhttpd_debug')or0iftheoptionisNULL.stop():Stopstheserver.add(app=NULL,name=NULL):AddsanewRookapplicationtotheserver.appcanbeanRhttpdAppobjectoranyRookapplication.nameisacharacterstringandisignoredifappisanRhttpdAppobject.SeeAlsoRhttpdAppExamples#CreateanRhttpdobjectandstarttheinternalwebserver.Notethat#iftherearenoapplicationsadded,thenthedefaultRookTestappin#system.file('exampleApps/RookTestApp.R',package='Rook')isautomatically#added.sRhttpd$new()##Notrun:s$start(quiet=TRUE)s$browse(1)##End(Notrun)s$print()#BesuretoinstalltheHmiscpackagebeforeinstallingandrunning#thisapplication.Youwillwantto;it'saprettygoodone.#s$add(#app=system.file('exampleApps/Hmisc/config.R',package='Rook'),#name='hmisc')s$add(app=system.file('exampleApps/helloworld.R',package='Rook'),name='hello')s$add( RhttpdApp-class17app=system.file('exampleApps/helloworldref.R',package='Rook'),name='helloref')s$add(app=system.file('exampleApps/summary.R',package='Rook'),name='summary')s$print()#Stopstheserverbutdoesn'tuninstalltheapp##Notrun:s$stop()##End(Notrun)s$remove(all=TRUE)rm(s) RhttpdApp-classClassRhttpdApp DescriptionCreatesaRookapplicationreadytoaddtoanRhttpdserver.DetailsTheinternalwebserverallowsdispatchingtouser-denedclosureslocatedintools:::.httpd.handlers.env.Forinstance,ifahandlernamed'foo'isplacedthere,thentheurlpathtothathandleris/custom/foo.RhttpdAppalongwithRhttpdhidethesedetailsbyallowingausertocreateapplicationobjectsspecifyingonlytheirnameandtheapplication.Thereiscurrentlyalimitof63charactersorlessforapplicationnames.NOTE:Whenaleisgivenasthevalueoftheappargumenttonew(),itismonitoredfortimestampchanges.Ifachangeoccursinthemodicationtimeasreturnedbyfile.info,thentheleissourcedpriortohandlingsubsequentrequests.Methodsnew(app,name):CreatesanobjectofclassRhttpdApp.ArgumentappcanbeanyRookawareobjectoritcanbealocationtoalewhosesourcecreatesaRookawareobject.Thatobjectmustbenamedeither'app'orthevalueofname.nameisacharactervector.SeeAlsoRhttpd. 18RhttpdInputStream-classExamplessRhttpd$new()s$add(RhttpdApp$new(name='summary',app=system.file('exampleApps/summary.R',package='Rook')))##Notrun:s$start(quiet=TRUE)s$browse(1)##End(Notrun)s$remove(all=TRUE)#Stopstheserverbutdoesn'tuninstalltheapp##Notrun:s$stop()##End(Notrun)s$remove(all=TRUE)rm(s) RhttpdErrorStream-classClassRhttpdErrorStream DescriptionAninternalclassusedbyRhttpd.ExamplesshowClass("RhttpdErrorStream") RhttpdInputStream-classClassRhttpdInputStream DescriptionAninternalclassusedbyRhttpd.ExamplesshowClass("RhttpdInputStream") Server19 ServerRookServerObject DescriptionServerisanobjectexportedbyRookthathasnovaluetotheuser.Itismainlyusedbywebserversfortheirconvenience.Toseeanexampleofhowitmaybeused,seerApache.Rintheinst/serversdirectory. Static-classClassStatic DescriptionAMiddlewareclassforservingstaticlesfromarootdirectorygivenasetofurlpaths.Methodsnew(urls,root):Createsanewobject.urlsisacharactervectorwhoseelementsmuststartwitha'/'.rootisalength1charactervectorwhosevaluemustbeavaliddirectory.SeeAlsoSeeBuilderforanexample. suspend_consoleSuspendtheRconsole DescriptionCallsSys.sleepinanever-endingwhilelooptomimicsuspensionoftheRconsole.Usagesuspend_console()ValueNovalueiseverreturned.SeeAlsoRook. 20URLMap-class URLMap-classClassURLMap DescriptionARookapplicationthatmapsurlpathstootherRookapplications.Methodsnew(...):CreatesaRookapplication.AllargumentsmustbeRookapplicationsandnamedasintheexample.SeeAlsoRhttpd.ExamplessRhttpd$new()s$add(name="pingpong",app=Rook::URLMap$new('/ping'=function(env){reqRook::Request$new(env)resRook::Response$new()res$write(sprintf('&#xh100; -50;�&#x/a00;&#x/h10;href="%s"Pong',req$to_url("/pong")))res$finish()},'/pong'=function(env){reqRook::Request$new(env)resRook::Response$new()res$write(sprintf('&#xh100; -50;�&#x/a00;&#x/h10;href="%s"Ping',req$to_url("/ping")))res$finish()},'/?'=function(env){reqRook::Request$new(env)resRook::Response$new()res$redirect(req$to_url('/pong'))res$finish()}))##Notrun:s$start(quiet=TRUE)s$browse('pingpong')##End(Notrun)s$remove('pingpong')##Notrun:s$stop() Utils-class21##End(Notrun)rm(s) Utils-classClassUtils DescriptionAconvenienceobjectforworkingwithvariousaspectsofwebrequestsandresponses.Methodsbytesize(string=NULL):Returnssizeinbytesforstring,acharactervector.unescape(s=NULL):returnstheurldecodedvalueofthecharactervectors.Alsoreplacesthe'+'characterwithaspace.status_code(status=NULL):returnsintegervalueforthegivenHTTPstatus,whichcaneitherbenumericororacharactervectordescribingthestatus.Returnsas.integer(500)ifstatusisNULL.escape_html(string=NULL):replaces"&",",&#x"]TJ;&#x/F37;&#x 9.9;ئ ;&#xTf 1;.94; 0 ;&#xTd [;"","'",and'"'withentityequivalents.raw.match(needle=NULL,haystack=NULL,all=TRUE):returnsindexpositionofneedleinhaystack.Allmatchedindexesarereturnedbydefault.needleiseitherarawvectororcharacterstring.haystackisarawvector.parse_query(qs=NULL,d=DEFAULT_SEP):Createsanamedlistfromthethequerystringqs.distheseparatorvalueanddefaultsto'[&;]*'.rfc2822(ts=NULL):FormatstsinRFC2822time.tsmustbeaPOSIXtobject.escape(s=NULL):Transformsanynon-printablecharactersfoundinstotheirpercent-encodedequivalents.build_query(params=NULL):Createsaquerystringfromthenamedlistgiveninparams.timezero():ReturnsaPOSIXctobjectsettoUNIXepoch.set_cookie_header(header,key,value,expires,path,domain,secure,httpOnly):SetsanHTTPcookieheaderintheenvironmentheader.Allargumentsexceptexpiresarelength1charactervectors,whileexpiresmustbeaPOSIXctobject.delete_cookie_header(header,key,value,expires,path,domain,secure,httpOnly):DeletestheHTTPcookieheader.SeeAlsoMultipart. 22Utils-classExamplesUtils$bytesize('foo')Utils$escape('foobar')Utils$unescape('foo+bar')Utils$escape_html('fooºr0;')Utils$escape('fooºr0;')Utils$escape('ºr0;foo\n')Utils$status_code('OK')Utils$status_code('Found')Utils$status_code('NotFound')xUtils$parse_query('foo=1&bar=baz')xUtils$rfc2822(Sys.time())Utils$timezero()Utils$build_query(x)rm(x) IndexTopicclassesApp-class,4Brewery-class,5Builder-class,6File-class,7Middleware-class,8Mime-class,9Multipart-class,10Redirect-class,11Request-class,11Response-class,14Rhttpd-class,15RhttpdApp-class,17RhttpdErrorStream-class,18RhttpdInputStream-class,18Server,19Static-class,19URLMap-class,20Utils-class,21Topicfunctionis_rookable,8suspend_console,19TopicpackageRook-package,2App(App-class),4App-class,4brew,5Brewery,6,8,11Brewery(Brewery-class),5Brewery-class,5browseURL,15Builder,5,19Builder(Builder-class),6Builder-class,6cat,4File(File-class),7File-class,7file.info,17is_rookable,5,8Middleware,4,5,19Middleware(Middleware-class),8Middleware-class,8Mime(Mime-class),9Mime-class,9Multipart,21Multipart(Multipart-class),10Multipart-class,10POSIXt,21Redirect,5,6Redirect(Redirect-class),11Redirect-class,11regexp,5Request,5,10,14Request(Request-class),11Request-class,11Response,5,10,12Response(Response-class),14Response-class,14Rhttpd,2,5–7,10,12,14,17,18,20Rhttpd(Rhttpd-class),15Rhttpd-class,15RhttpdApp,16RhttpdApp(RhttpdApp-class),17RhttpdApp-class,17RhttpdErrorStream(RhttpdErrorStream-class),18RhttpdErrorStream-class,18RhttpdInputStream,12RhttpdInputStream(RhttpdInputStream-class),18RhttpdInputStream-class,18Rook,8,10,11,14,17,19,2023 24INDEXRook(Rook-package),2Rook-package,2Server,19Static,6,8Static(Static-class),19Static-class,19suspend_console,19URLMap(URLMap-class),20URLMap-class,20Utils(Utils-class),21Utils-class,21