web.texi 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896
  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Guile Reference Manual.
  3. @c Copyright (C) 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
  4. @c See the file guile.texi for copying conditions.
  5. @node Web
  6. @section @acronym{HTTP}, the Web, and All That
  7. @cindex Web
  8. @cindex WWW
  9. @cindex HTTP
  10. It has always been possible to connect computers together and share
  11. information between them, but the rise of the World Wide Web over the
  12. last couple of decades has made it much easier to do so. The result is
  13. a richly connected network of computation, in which Guile forms a part.
  14. By ``the web'', we mean the HTTP protocol@footnote{Yes, the P is for
  15. protocol, but this phrase appears repeatedly in RFC 2616.} as handled by
  16. servers, clients, proxies, caches, and the various kinds of messages and
  17. message components that can be sent and received by that protocol,
  18. notably HTML.
  19. On one level, the web is text in motion: the protocols themselves are
  20. textual (though the payload may be binary), and it's possible to create
  21. a socket and speak text to the web. But such an approach is obviously
  22. primitive. This section details the higher-level data types and
  23. operations provided by Guile: URIs, HTTP request and response records,
  24. and a conventional web server implementation.
  25. The material in this section is arranged in ascending order, in which
  26. later concepts build on previous ones. If you prefer to start with the
  27. highest-level perspective, @pxref{Web Examples}, and work your way
  28. back.
  29. @menu
  30. * Types and the Web:: Types prevent bugs and security problems.
  31. * URIs:: Universal Resource Identifiers.
  32. * HTTP:: The Hyper-Text Transfer Protocol.
  33. * HTTP Headers:: How Guile represents specific header values.
  34. * Transfer Codings:: HTTP Transfer Codings.
  35. * Requests:: HTTP requests.
  36. * Responses:: HTTP responses.
  37. * Web Client:: Accessing web resources over HTTP.
  38. * Web Server:: Serving HTTP to the internet.
  39. * Web Examples:: How to use this thing.
  40. @end menu
  41. @node Types and the Web
  42. @subsection Types and the Web
  43. It is a truth universally acknowledged, that a program with good use of
  44. data types, will be free from many common bugs. Unfortunately, the
  45. common practice in web programming seems to ignore this maxim. This
  46. subsection makes the case for expressive data types in web programming.
  47. By ``expressive data types'', we mean that the data types @emph{say}
  48. something about how a program solves a problem. For example, if we
  49. choose to represent dates using SRFI 19 date records (@pxref{SRFI-19}),
  50. this indicates that there is a part of the program that will always have
  51. valid dates. Error handling for a number of basic cases, like invalid
  52. dates, occurs on the boundary in which we produce a SRFI 19 date record
  53. from other types, like strings.
  54. With regards to the web, data types are helpful in the two broad phases
  55. of HTTP messages: parsing and generation.
  56. Consider a server, which has to parse a request, and produce a response.
  57. Guile will parse the request into an HTTP request object
  58. (@pxref{Requests}), with each header parsed into an appropriate Scheme
  59. data type. This transition from an incoming stream of characters to
  60. typed data is a state change in a program---the strings might parse, or
  61. they might not, and something has to happen if they do not. (Guile
  62. throws an error in this case.) But after you have the parsed request,
  63. ``client'' code (code built on top of the Guile web framework) will not
  64. have to check for syntactic validity. The types already make this
  65. information manifest.
  66. This state change on the parsing boundary makes programs more robust,
  67. as they themselves are freed from the need to do a number of common
  68. error checks, and they can use normal Scheme procedures to handle a
  69. request instead of ad-hoc string parsers.
  70. The need for types on the response generation side (in a server) is more
  71. subtle, though not less important. Consider the example of a POST
  72. handler, which prints out the text that a user submits from a form.
  73. Such a handler might include a procedure like this:
  74. @example
  75. ;; First, a helper procedure
  76. (define (para . contents)
  77. (string-append "<p>" (string-concatenate contents) "</p>"))
  78. ;; Now the meat of our simple web application
  79. (define (you-said text)
  80. (para "You said: " text))
  81. (display (you-said "Hi!"))
  82. @print{} <p>You said: Hi!</p>
  83. @end example
  84. This is a perfectly valid implementation, provided that the incoming
  85. text does not contain the special HTML characters @samp{<}, @samp{>}, or
  86. @samp{&}. But this provision of a restricted character set is not
  87. reflected anywhere in the program itself: we must @emph{assume} that the
  88. programmer understands this, and performs the check elsewhere.
  89. Unfortunately, the short history of the practice of programming does not
  90. bear out this assumption. A @dfn{cross-site scripting} (@acronym{XSS})
  91. vulnerability is just such a common error in which unfiltered user input
  92. is allowed into the output. A user could submit a crafted comment to
  93. your web site which results in visitors running malicious Javascript,
  94. within the security context of your domain:
  95. @example
  96. (display (you-said "<script src=\"http://bad.com/nasty.js\" />"))
  97. @print{} <p>You said: <script src="http://bad.com/nasty.js" /></p>
  98. @end example
  99. The fundamental problem here is that both user data and the program
  100. template are represented using strings. This identity means that types
  101. can't help the programmer to make a distinction between these two, so
  102. they get confused.
  103. There are a number of possible solutions, but perhaps the best is to
  104. treat HTML not as strings, but as native s-expressions: as SXML. The
  105. basic idea is that HTML is either text, represented by a string, or an
  106. element, represented as a tagged list. So @samp{foo} becomes
  107. @samp{"foo"}, and @samp{<b>foo</b>} becomes @samp{(b "foo")}.
  108. Attributes, if present, go in a tagged list headed by @samp{@@}, like
  109. @samp{(img (@@ (src "http://example.com/foo.png")))}. @xref{SXML}, for
  110. more information.
  111. The good thing about SXML is that HTML elements cannot be confused with
  112. text. Let's make a new definition of @code{para}:
  113. @example
  114. (define (para . contents)
  115. `(p ,@@contents))
  116. (use-modules (sxml simple))
  117. (sxml->xml (you-said "Hi!"))
  118. @print{} <p>You said: Hi!</p>
  119. (sxml->xml (you-said "<i>Rats, foiled again!</i>"))
  120. @print{} <p>You said: &lt;i&gt;Rats, foiled again!&lt;/i&gt;</p>
  121. @end example
  122. So we see in the second example that HTML elements cannot be unwittingly
  123. introduced into the output. However it is now perfectly acceptable to
  124. pass SXML to @code{you-said}; in fact, that is the big advantage of SXML
  125. over everything-as-a-string.
  126. @example
  127. (sxml->xml (you-said (you-said "<Hi!>")))
  128. @print{} <p>You said: <p>You said: &lt;Hi!&gt;</p></p>
  129. @end example
  130. The SXML types allow procedures to @emph{compose}. The types make
  131. manifest which parts are HTML elements, and which are text. So you
  132. needn't worry about escaping user input; the type transition back to a
  133. string handles that for you. @acronym{XSS} vulnerabilities are a thing
  134. of the past.
  135. Well. That's all very nice and opinionated and such, but how do I use
  136. the thing? Read on!
  137. @node URIs
  138. @subsection Universal Resource Identifiers
  139. Guile provides a standard data type for Universal Resource Identifiers
  140. (URIs), as defined in RFC 3986.
  141. The generic URI syntax is as follows:
  142. @example
  143. URI := scheme ":" ["//" [userinfo "@@"] host [":" port]] path \
  144. [ "?" query ] [ "#" fragment ]
  145. @end example
  146. For example, in the URI, @indicateurl{http://www.gnu.org/help/}, the
  147. scheme is @code{http}, the host is @code{www.gnu.org}, the path is
  148. @code{/help/}, and there is no userinfo, port, query, or fragment. All
  149. URIs have a scheme and a path (though the path might be empty). Some
  150. URIs have a host, and some of those have ports and userinfo. Any URI
  151. might have a query part or a fragment.
  152. Userinfo is something of an abstraction, as some legacy URI schemes
  153. allowed userinfo of the form @code{@var{username}:@var{passwd}}. But
  154. since passwords do not belong in URIs, the RFC does not want to condone
  155. this practice, so it calls anything before the @code{@@} sign
  156. @dfn{userinfo}.
  157. Properly speaking, a fragment is not part of a URI. For example, when a
  158. web browser follows a link to @indicateurl{http://example.com/#foo}, it
  159. sends a request for @indicateurl{http://example.com/}, then looks in the
  160. resulting page for the fragment identified @code{foo} reference. A
  161. fragment identifies a part of a resource, not the resource itself. But
  162. it is useful to have a fragment field in the URI record itself, so we
  163. hope you will forgive the inconsistency.
  164. @example
  165. (use-modules (web uri))
  166. @end example
  167. The following procedures can be found in the @code{(web uri)}
  168. module. Load it into your Guile, using a form like the above, to have
  169. access to them.
  170. @deffn {Scheme Procedure} build-uri scheme @
  171. [#:userinfo=@code{#f}] [#:host=@code{#f}] [#:port=@code{#f}] @
  172. [#:path=@code{""}] [#:query=@code{#f}] [#:fragment=@code{#f}] @
  173. [#:validate?=@code{#t}]
  174. Construct a URI object. @var{scheme} should be a symbol, @var{port}
  175. either a positive, exact integer or @code{#f}, and the rest of the
  176. fields are either strings or @code{#f}. If @var{validate?} is true,
  177. also run some consistency checks to make sure that the constructed URI
  178. is valid.
  179. @end deffn
  180. @deffn {Scheme Procedure} uri? obj
  181. @deffnx {Scheme Procedure} uri-scheme uri
  182. @deffnx {Scheme Procedure} uri-userinfo uri
  183. @deffnx {Scheme Procedure} uri-host uri
  184. @deffnx {Scheme Procedure} uri-port uri
  185. @deffnx {Scheme Procedure} uri-path uri
  186. @deffnx {Scheme Procedure} uri-query uri
  187. @deffnx {Scheme Procedure} uri-fragment uri
  188. A predicate and field accessors for the URI record type. The URI scheme
  189. will be a symbol, the port either a positive, exact integer or @code{#f},
  190. and the rest either strings or @code{#f} if not present.
  191. @end deffn
  192. @deffn {Scheme Procedure} string->uri string
  193. Parse @var{string} into a URI object. Return @code{#f} if the string
  194. could not be parsed.
  195. @end deffn
  196. @deffn {Scheme Procedure} uri->string uri
  197. Serialize @var{uri} to a string. If the URI has a port that is the
  198. default port for its scheme, the port is not included in the
  199. serialization.
  200. @end deffn
  201. @deffn {Scheme Procedure} declare-default-port! scheme port
  202. Declare a default port for the given URI scheme.
  203. @end deffn
  204. @deffn {Scheme Procedure} uri-decode str [#:encoding=@code{"utf-8"}]
  205. Percent-decode the given @var{str}, according to @var{encoding}, which
  206. should be the name of a character encoding.
  207. Note that this function should not generally be applied to a full URI
  208. string. For paths, use @code{split-and-decode-uri-path} instead. For
  209. query strings, split the query on @code{&} and @code{=} boundaries, and
  210. decode the components separately.
  211. Note also that percent-encoded strings encode @emph{bytes}, not
  212. characters. There is no guarantee that a given byte sequence is a valid
  213. string encoding. Therefore this routine may signal an error if the
  214. decoded bytes are not valid for the given encoding. Pass @code{#f} for
  215. @var{encoding} if you want decoded bytes as a bytevector directly.
  216. @xref{Ports, @code{set-port-encoding!}}, for more information on
  217. character encodings.
  218. Returns a string of the decoded characters, or a bytevector if
  219. @var{encoding} was @code{#f}.
  220. @end deffn
  221. Fixme: clarify return type. indicate default values. type of
  222. unescaped-chars.
  223. @deffn {Scheme Procedure} uri-encode str [#:encoding=@code{"utf-8"}] [#:unescaped-chars]
  224. Percent-encode any character not in the character set,
  225. @var{unescaped-chars}.
  226. The default character set includes alphanumerics from ASCII, as well as
  227. the special characters @samp{-}, @samp{.}, @samp{_}, and @samp{~}. Any
  228. other character will be percent-encoded, by writing out the character to
  229. a bytevector within the given @var{encoding}, then encoding each byte as
  230. @code{%@var{HH}}, where @var{HH} is the hexadecimal representation of
  231. the byte.
  232. @end deffn
  233. @deffn {Scheme Procedure} split-and-decode-uri-path path
  234. Split @var{path} into its components, and decode each component,
  235. removing empty components.
  236. For example, @code{"/foo/bar%20baz/"} decodes to the two-element list,
  237. @code{("foo" "bar baz")}.
  238. @end deffn
  239. @deffn {Scheme Procedure} encode-and-join-uri-path parts
  240. URI-encode each element of @var{parts}, which should be a list of
  241. strings, and join the parts together with @code{/} as a delimiter.
  242. For example, the list @code{("scrambled eggs" "biscuits&gravy")} encodes
  243. as @code{"scrambled%20eggs/biscuits%26gravy"}.
  244. @end deffn
  245. @node HTTP
  246. @subsection The Hyper-Text Transfer Protocol
  247. The initial motivation for including web functionality in Guile, rather
  248. than rely on an external package, was to establish a standard base on
  249. which people can share code. To that end, we continue the focus on data
  250. types by providing a number of low-level parsers and unparsers for
  251. elements of the HTTP protocol.
  252. If you are want to skip the low-level details for now and move on to web
  253. pages, @pxref{Web Client}, and @pxref{Web Server}. Otherwise, load the
  254. HTTP module, and read on.
  255. @example
  256. (use-modules (web http))
  257. @end example
  258. The focus of the @code{(web http)} module is to parse and unparse
  259. standard HTTP headers, representing them to Guile as native data
  260. structures. For example, a @code{Date:} header will be represented as a
  261. SRFI-19 date record (@pxref{SRFI-19}), rather than as a string.
  262. Guile tries to follow RFCs fairly strictly---the road to perdition being
  263. paved with compatibility hacks---though some allowances are made for
  264. not-too-divergent texts.
  265. Header names are represented as lower-case symbols.
  266. @deffn {Scheme Procedure} string->header name
  267. Parse @var{name} to a symbolic header name.
  268. @end deffn
  269. @deffn {Scheme Procedure} header->string sym
  270. Return the string form for the header named @var{sym}.
  271. @end deffn
  272. For example:
  273. @example
  274. (string->header "Content-Length")
  275. @result{} content-length
  276. (header->string 'content-length)
  277. @result{} "Content-Length"
  278. (string->header "FOO")
  279. @result{} foo
  280. (header->string 'foo)
  281. @result{} "Foo"
  282. @end example
  283. Guile keeps a registry of known headers, their string names, and some
  284. parsing and serialization procedures. If a header is unknown, its
  285. string name is simply its symbol name in title-case.
  286. @deffn {Scheme Procedure} known-header? sym
  287. Return @code{#t} if @var{sym} is a known header, with associated
  288. parsers and serialization procedures, or @code{#f} otherwise.
  289. @end deffn
  290. @deffn {Scheme Procedure} header-parser sym
  291. Return the value parser for headers named @var{sym}. The result is a
  292. procedure that takes one argument, a string, and returns the parsed
  293. value. If the header isn't known to Guile, a default parser is returned
  294. that passes through the string unchanged.
  295. @end deffn
  296. @deffn {Scheme Procedure} header-validator sym
  297. Return a predicate which returns @code{#t} if the given value is valid
  298. for headers named @var{sym}. The default validator for unknown headers
  299. is @code{string?}.
  300. @end deffn
  301. @deffn {Scheme Procedure} header-writer sym
  302. Return a procedure that writes values for headers named @var{sym} to a
  303. port. The resulting procedure takes two arguments: a value and a port.
  304. The default writer is @code{display}.
  305. @end deffn
  306. For more on the set of headers that Guile knows about out of the box,
  307. @pxref{HTTP Headers}. To add your own, use the @code{declare-header!}
  308. procedure:
  309. @deffn {Scheme Procedure} declare-header! name parser validator writer @
  310. [#:multiple?=@code{#f}]
  311. Declare a parser, validator, and writer for a given header.
  312. @end deffn
  313. For example, let's say you are running a web server behind some sort of
  314. proxy, and your proxy adds an @code{X-Client-Address} header, indicating
  315. the IPv4 address of the original client. You would like for the HTTP
  316. request record to parse out this header to a Scheme value, instead of
  317. leaving it as a string. You could register this header with Guile's
  318. HTTP stack like this:
  319. @example
  320. (declare-header! "X-Client-Address"
  321. (lambda (str)
  322. (inet-aton str))
  323. (lambda (ip)
  324. (and (integer? ip) (exact? ip) (<= 0 ip #xffffffff)))
  325. (lambda (ip port)
  326. (display (inet-ntoa ip) port)))
  327. @end example
  328. @deffn {Scheme Procedure} declare-opaque-header! name
  329. A specialised version of @code{declare-header!} for the case in which
  330. you want a header's value to be returned/written ``as-is''.
  331. @end deffn
  332. @deffn {Scheme Procedure} valid-header? sym val
  333. Return a true value if @var{val} is a valid Scheme value for the header
  334. with name @var{sym}, or @code{#f} otherwise.
  335. @end deffn
  336. Now that we have a generic interface for reading and writing headers, we
  337. do just that.
  338. @deffn {Scheme Procedure} read-header port
  339. Read one HTTP header from @var{port}. Return two values: the header
  340. name and the parsed Scheme value. May raise an exception if the header
  341. was known but the value was invalid.
  342. Returns the end-of-file object for both values if the end of the message
  343. body was reached (i.e., a blank line).
  344. @end deffn
  345. @deffn {Scheme Procedure} parse-header name val
  346. Parse @var{val}, a string, with the parser for the header named
  347. @var{name}. Returns the parsed value.
  348. @end deffn
  349. @deffn {Scheme Procedure} write-header name val port
  350. Write the given header name and value to @var{port}, using the writer
  351. from @code{header-writer}.
  352. @end deffn
  353. @deffn {Scheme Procedure} read-headers port
  354. Read the headers of an HTTP message from @var{port}, returning them
  355. as an ordered alist.
  356. @end deffn
  357. @deffn {Scheme Procedure} write-headers headers port
  358. Write the given header alist to @var{port}. Doesn't write the final
  359. @samp{\r\n}, as the user might want to add another header.
  360. @end deffn
  361. The @code{(web http)} module also has some utility procedures to read
  362. and write request and response lines.
  363. @deffn {Scheme Procedure} parse-http-method str [start] [end]
  364. Parse an HTTP method from @var{str}. The result is an upper-case symbol,
  365. like @code{GET}.
  366. @end deffn
  367. @deffn {Scheme Procedure} parse-http-version str [start] [end]
  368. Parse an HTTP version from @var{str}, returning it as a major--minor
  369. pair. For example, @code{HTTP/1.1} parses as the pair of integers,
  370. @code{(1 . 1)}.
  371. @end deffn
  372. @deffn {Scheme Procedure} parse-request-uri str [start] [end]
  373. Parse a URI from an HTTP request line. Note that URIs in requests do not
  374. have to have a scheme or host name. The result is a URI object.
  375. @end deffn
  376. @deffn {Scheme Procedure} read-request-line port
  377. Read the first line of an HTTP request from @var{port}, returning three
  378. values: the method, the URI, and the version.
  379. @end deffn
  380. @deffn {Scheme Procedure} write-request-line method uri version port
  381. Write the first line of an HTTP request to @var{port}.
  382. @end deffn
  383. @deffn {Scheme Procedure} read-response-line port
  384. Read the first line of an HTTP response from @var{port}, returning three
  385. values: the HTTP version, the response code, and the ``reason phrase''.
  386. @end deffn
  387. @deffn {Scheme Procedure} write-response-line version code reason-phrase port
  388. Write the first line of an HTTP response to @var{port}.
  389. @end deffn
  390. @node HTTP Headers
  391. @subsection HTTP Headers
  392. In addition to defining the infrastructure to parse headers, the
  393. @code{(web http)} module defines specific parsers and unparsers for all
  394. headers defined in the HTTP/1.1 standard.
  395. For example, if you receive a header named @samp{Accept-Language} with a
  396. value @samp{en, es;q=0.8}, Guile parses it as a quality list (defined
  397. below):
  398. @example
  399. (parse-header 'accept-language "en, es;q=0.8")
  400. @result{} ((1000 . "en") (800 . "es"))
  401. @end example
  402. The format of the value for @samp{Accept-Language} headers is defined
  403. below, along with all other headers defined in the HTTP standard. (If
  404. the header were unknown, the value would have been returned as a
  405. string.)
  406. For brevity, the header definitions below are given in the form,
  407. @var{Type} @code{@var{name}}, indicating that values for the header
  408. @code{@var{name}} will be of the given @var{Type}. Since Guile
  409. internally treats header names in lower case, in this document we give
  410. types title-cased names. A short description of the each header's
  411. purpose and an example follow.
  412. For full details on the meanings of all of these headers, see the HTTP
  413. 1.1 standard, RFC 2616.
  414. @subsubsection HTTP Header Types
  415. Here we define the types that are used below, when defining headers.
  416. @deftp {HTTP Header Type} Date
  417. A SRFI-19 date.
  418. @end deftp
  419. @deftp {HTTP Header Type} KVList
  420. A list whose elements are keys or key-value pairs. Keys are parsed to
  421. symbols. Values are strings by default. Non-string values are the
  422. exception, and are mentioned explicitly below, as appropriate.
  423. @end deftp
  424. @deftp {HTTP Header Type} SList
  425. A list of strings.
  426. @end deftp
  427. @deftp {HTTP Header Type} Quality
  428. An exact integer between 0 and 1000. Qualities are used to express
  429. preference, given multiple options. An option with a quality of 870,
  430. for example, is preferred over an option with quality 500.
  431. (Qualities are written out over the wire as numbers between 0.0 and
  432. 1.0, but since the standard only allows three digits after the decimal,
  433. it's equivalent to integers between 0 and 1000, so that's what Guile
  434. uses.)
  435. @end deftp
  436. @deftp {HTTP Header Type} QList
  437. A quality list: a list of pairs, the car of which is a quality, and the
  438. cdr a string. Used to express a list of options, along with their
  439. qualities.
  440. @end deftp
  441. @deftp {HTTP Header Type} ETag
  442. An entity tag, represented as a pair. The car of the pair is an opaque
  443. string, and the cdr is @code{#t} if the entity tag is a ``strong'' entity
  444. tag, and @code{#f} otherwise.
  445. @end deftp
  446. @subsubsection General Headers
  447. General HTTP headers may be present in any HTTP message.
  448. @deftypevr {HTTP Header} KVList cache-control
  449. A key-value list of cache-control directives. See RFC 2616, for more
  450. details.
  451. If present, parameters to @code{max-age}, @code{max-stale},
  452. @code{min-fresh}, and @code{s-maxage} are all parsed as non-negative
  453. integers.
  454. If present, parameters to @code{private} and @code{no-cache} are parsed
  455. as lists of header names, as symbols.
  456. @example
  457. (parse-header 'cache-control "no-cache,no-store"
  458. @result{} (no-cache no-store)
  459. (parse-header 'cache-control "no-cache=\"Authorization,Date\",no-store"
  460. @result{} ((no-cache . (authorization date)) no-store)
  461. (parse-header 'cache-control "no-cache=\"Authorization,Date\",max-age=10"
  462. @result{} ((no-cache . (authorization date)) (max-age . 10))
  463. @end example
  464. @end deftypevr
  465. @deftypevr {HTTP Header} List connection
  466. A list of header names that apply only to this HTTP connection, as
  467. symbols. Additionally, the symbol @samp{close} may be present, to
  468. indicate that the server should close the connection after responding to
  469. the request.
  470. @example
  471. (parse-header 'connection "close")
  472. @result{} (close)
  473. @end example
  474. @end deftypevr
  475. @deftypevr {HTTP Header} Date date
  476. The date that a given HTTP message was originated.
  477. @example
  478. (parse-header 'date "Tue, 15 Nov 1994 08:12:31 GMT")
  479. @result{} #<date ...>
  480. @end example
  481. @end deftypevr
  482. @deftypevr {HTTP Header} KVList pragma
  483. A key-value list of implementation-specific directives.
  484. @example
  485. (parse-header 'pragma "no-cache, broccoli=tasty")
  486. @result{} (no-cache (broccoli . "tasty"))
  487. @end example
  488. @end deftypevr
  489. @deftypevr {HTTP Header} List trailer
  490. A list of header names which will appear after the message body, instead
  491. of with the message headers.
  492. @example
  493. (parse-header 'trailer "ETag")
  494. @result{} (etag)
  495. @end example
  496. @end deftypevr
  497. @deftypevr {HTTP Header} List transfer-encoding
  498. A list of transfer codings, expressed as key-value lists. The only
  499. transfer coding defined by the specification is @code{chunked}.
  500. @example
  501. (parse-header 'transfer-encoding "chunked")
  502. @result{} ((chunked))
  503. @end example
  504. @end deftypevr
  505. @deftypevr {HTTP Header} List upgrade
  506. A list of strings, indicating additional protocols that a server could use
  507. in response to a request.
  508. @example
  509. (parse-header 'upgrade "WebSocket")
  510. @result{} ("WebSocket")
  511. @end example
  512. @end deftypevr
  513. FIXME: parse out more fully?
  514. @deftypevr {HTTP Header} List via
  515. A list of strings, indicating the protocol versions and hosts of
  516. intermediate servers and proxies. There may be multiple @code{via}
  517. headers in one message.
  518. @example
  519. (parse-header 'via "1.0 venus, 1.1 mars")
  520. @result{} ("1.0 venus" "1.1 mars")
  521. @end example
  522. @end deftypevr
  523. @deftypevr {HTTP Header} List warning
  524. A list of warnings given by a server or intermediate proxy. Each
  525. warning is a itself a list of four elements: a code, as an exact integer
  526. between 0 and 1000, a host as a string, the warning text as a string,
  527. and either @code{#f} or a SRFI-19 date.
  528. There may be multiple @code{warning} headers in one message.
  529. @example
  530. (parse-header 'warning "123 foo \"core breach imminent\"")
  531. @result{} ((123 "foo" "core-breach imminent" #f))
  532. @end example
  533. @end deftypevr
  534. @subsubsection Entity Headers
  535. Entity headers may be present in any HTTP message, and refer to the
  536. resource referenced in the HTTP request or response.
  537. @deftypevr {HTTP Header} List allow
  538. A list of allowed methods on a given resource, as symbols.
  539. @example
  540. (parse-header 'allow "GET, HEAD")
  541. @result{} (GET HEAD)
  542. @end example
  543. @end deftypevr
  544. @deftypevr {HTTP Header} List content-encoding
  545. A list of content codings, as symbols.
  546. @example
  547. (parse-header 'content-encoding "gzip")
  548. @result{} (gzip)
  549. @end example
  550. @end deftypevr
  551. @deftypevr {HTTP Header} List content-language
  552. The languages that a resource is in, as strings.
  553. @example
  554. (parse-header 'content-language "en")
  555. @result{} ("en")
  556. @end example
  557. @end deftypevr
  558. @deftypevr {HTTP Header} UInt content-length
  559. The number of bytes in a resource, as an exact, non-negative integer.
  560. @example
  561. (parse-header 'content-length "300")
  562. @result{} 300
  563. @end example
  564. @end deftypevr
  565. @deftypevr {HTTP Header} URI content-location
  566. The canonical URI for a resource, in the case that it is also accessible
  567. from a different URI.
  568. @example
  569. (parse-header 'content-location "http://example.com/foo")
  570. @result{} #<<uri> ...>
  571. @end example
  572. @end deftypevr
  573. @deftypevr {HTTP Header} String content-md5
  574. The MD5 digest of a resource.
  575. @example
  576. (parse-header 'content-md5 "ffaea1a79810785575e29e2bd45e2fa5")
  577. @result{} "ffaea1a79810785575e29e2bd45e2fa5"
  578. @end example
  579. @end deftypevr
  580. @deftypevr {HTTP Header} List content-range
  581. A range specification, as a list of three elements: the symbol
  582. @code{bytes}, either the symbol @code{*} or a pair of integers,
  583. indicating the byte rage, and either @code{*} or an integer, for the
  584. instance length. Used to indicate that a response only includes part of
  585. a resource.
  586. @example
  587. (parse-header 'content-range "bytes 10-20/*")
  588. @result{} (bytes (10 . 20) *)
  589. @end example
  590. @end deftypevr
  591. @deftypevr {HTTP Header} List content-type
  592. The MIME type of a resource, as a symbol, along with any parameters.
  593. @example
  594. (parse-header 'content-length "text/plain")
  595. @result{} (text/plain)
  596. (parse-header 'content-length "text/plain;charset=utf-8")
  597. @result{} (text/plain (charset . "utf-8"))
  598. @end example
  599. Note that the @code{charset} parameter is something is a misnomer, and
  600. the HTTP specification admits this. It specifies the @emph{encoding} of
  601. the characters, not the character set.
  602. @end deftypevr
  603. @deftypevr {HTTP Header} Date expires
  604. The date/time after which the resource given in a response is considered
  605. stale.
  606. @example
  607. (parse-header 'expires "Tue, 15 Nov 1994 08:12:31 GMT")
  608. @result{} #<date ...>
  609. @end example
  610. @end deftypevr
  611. @deftypevr {HTTP Header} Date last-modified
  612. The date/time on which the resource given in a response was last
  613. modified.
  614. @example
  615. (parse-header 'expires "Tue, 15 Nov 1994 08:12:31 GMT")
  616. @result{} #<date ...>
  617. @end example
  618. @end deftypevr
  619. @subsubsection Request Headers
  620. Request headers may only appear in an HTTP request, not in a response.
  621. @deftypevr {HTTP Header} List accept
  622. A list of preferred media types for a response. Each element of the
  623. list is itself a list, in the same format as @code{content-type}.
  624. @example
  625. (parse-header 'accept "text/html,text/plain;charset=utf-8")
  626. @result{} ((text/html) (text/plain (charset . "utf-8")))
  627. @end example
  628. Preference is expressed with quality values:
  629. @example
  630. (parse-header 'accept "text/html;q=0.8,text/plain;q=0.6")
  631. @result{} ((text/html (q . 800)) (text/plain (q . 600)))
  632. @end example
  633. @end deftypevr
  634. @deftypevr {HTTP Header} QList accept-charset
  635. A quality list of acceptable charsets. Note again that what HTTP calls
  636. a ``charset'' is what Guile calls a ``character encoding''.
  637. @example
  638. (parse-header 'accept-charset "iso-8859-5, unicode-1-1;q=0.8")
  639. @result{} ((1000 . "iso-8859-5") (800 . "unicode-1-1"))
  640. @end example
  641. @end deftypevr
  642. @deftypevr {HTTP Header} QList accept-encoding
  643. A quality list of acceptable content codings.
  644. @example
  645. (parse-header 'accept-encoding "gzip,identity=0.8")
  646. @result{} ((1000 . "gzip") (800 . "identity"))
  647. @end example
  648. @end deftypevr
  649. @deftypevr {HTTP Header} QList accept-language
  650. A quality list of acceptable languages.
  651. @example
  652. (parse-header 'accept-language "cn,en=0.75")
  653. @result{} ((1000 . "cn") (750 . "en"))
  654. @end example
  655. @end deftypevr
  656. @deftypevr {HTTP Header} Pair authorization
  657. Authorization credentials. The car of the pair indicates the
  658. authentication scheme, like @code{basic}. For basic authentication, the
  659. cdr of the pair will be the base64-encoded @samp{@var{user}:@var{pass}}
  660. string. For other authentication schemes, like @code{digest}, the cdr
  661. will be a key-value list of credentials.
  662. @example
  663. (parse-header 'authorization "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
  664. @result{} (basic . "QWxhZGRpbjpvcGVuIHNlc2FtZQ==")
  665. @end example
  666. @end deftypevr
  667. @deftypevr {HTTP Header} List expect
  668. A list of expectations that a client has of a server. The expectations
  669. are key-value lists.
  670. @example
  671. (parse-header 'expect "100-continue")
  672. @result{} ((100-continue))
  673. @end example
  674. @end deftypevr
  675. @deftypevr {HTTP Header} String from
  676. The email address of a user making an HTTP request.
  677. @example
  678. (parse-header 'from "bob@@example.com")
  679. @result{} "bob@@example.com"
  680. @end example
  681. @end deftypevr
  682. @deftypevr {HTTP Header} Pair host
  683. The host for the resource being requested, as a hostname-port pair. If
  684. no port is given, the port is @code{#f}.
  685. @example
  686. (parse-header 'host "gnu.org:80")
  687. @result{} ("gnu.org" . 80)
  688. (parse-header 'host "gnu.org")
  689. @result{} ("gnu.org" . #f)
  690. @end example
  691. @end deftypevr
  692. @deftypevr {HTTP Header} *|List if-match
  693. A set of etags, indicating that the request should proceed if and only
  694. if the etag of the resource is in that set. Either the symbol @code{*},
  695. indicating any etag, or a list of entity tags.
  696. @example
  697. (parse-header 'if-match "*")
  698. @result{} *
  699. (parse-header 'if-match "asdfadf")
  700. @result{} (("asdfadf" . #t))
  701. (parse-header 'if-match W/"asdfadf")
  702. @result{} (("asdfadf" . #f))
  703. @end example
  704. @end deftypevr
  705. @deftypevr {HTTP Header} Date if-modified-since
  706. Indicates that a response should proceed if and only if the resource has
  707. been modified since the given date.
  708. @example
  709. (parse-header 'if-modified-since "Tue, 15 Nov 1994 08:12:31 GMT")
  710. @result{} #<date ...>
  711. @end example
  712. @end deftypevr
  713. @deftypevr {HTTP Header} *|List if-none-match
  714. A set of etags, indicating that the request should proceed if and only
  715. if the etag of the resource is not in the set. Either the symbol
  716. @code{*}, indicating any etag, or a list of entity tags.
  717. @example
  718. (parse-header 'if-none-match "*")
  719. @result{} *
  720. @end example
  721. @end deftypevr
  722. @deftypevr {HTTP Header} ETag|Date if-range
  723. Indicates that the range request should proceed if and only if the
  724. resource matches a modification date or an etag. Either an entity tag,
  725. or a SRFI-19 date.
  726. @example
  727. (parse-header 'if-range "\"original-etag\"")
  728. @result{} ("original-etag" . #t)
  729. @end example
  730. @end deftypevr
  731. @deftypevr {HTTP Header} Date if-unmodified-since
  732. Indicates that a response should proceed if and only if the resource has
  733. not been modified since the given date.
  734. @example
  735. (parse-header 'if-not-modified-since "Tue, 15 Nov 1994 08:12:31 GMT")
  736. @result{} #<date ...>
  737. @end example
  738. @end deftypevr
  739. @deftypevr {HTTP Header} UInt max-forwards
  740. The maximum number of proxy or gateway hops that a request should be
  741. subject to.
  742. @example
  743. (parse-header 'max-forwards "10")
  744. @result{} 10
  745. @end example
  746. @end deftypevr
  747. @deftypevr {HTTP Header} Pair proxy-authorization
  748. Authorization credentials for a proxy connection. See the documentation
  749. for @code{authorization} above for more information on the format.
  750. @example
  751. (parse-header 'proxy-authorization "Digest foo=bar,baz=qux"
  752. @result{} (digest (foo . "bar") (baz . "qux"))
  753. @end example
  754. @end deftypevr
  755. @deftypevr {HTTP Header} Pair range
  756. A range request, indicating that the client wants only part of a
  757. resource. The car of the pair is the symbol @code{bytes}, and the cdr
  758. is a list of pairs. Each element of the cdr indicates a range; the car
  759. is the first byte position and the cdr is the last byte position, as
  760. integers, or @code{#f} if not given.
  761. @example
  762. (parse-header 'range "bytes=10-30,50-")
  763. @result{} (bytes (10 . 30) (50 . #f))
  764. @end example
  765. @end deftypevr
  766. @deftypevr {HTTP Header} URI referer
  767. The URI of the resource that referred the user to this resource. The
  768. name of the header is a misspelling, but we are stuck with it.
  769. @example
  770. (parse-header 'referer "http://www.gnu.org/")
  771. @result{} #<uri ...>
  772. @end example
  773. @end deftypevr
  774. @deftypevr {HTTP Header} List te
  775. A list of transfer codings, expressed as key-value lists. A common
  776. transfer coding is @code{trailers}.
  777. @example
  778. (parse-header 'te "trailers")
  779. @result{} ((trailers))
  780. @end example
  781. @end deftypevr
  782. @deftypevr {HTTP Header} String user-agent
  783. A string indicating the user agent making the request. The
  784. specification defines a structured format for this header, but it is
  785. widely disregarded, so Guile does not attempt to parse strictly.
  786. @example
  787. (parse-header 'user-agent "Mozilla/5.0")
  788. @result{} "Mozilla/5.0"
  789. @end example
  790. @end deftypevr
  791. @subsubsection Response Headers
  792. @deftypevr {HTTP Header} List accept-ranges
  793. A list of range units that the server supports, as symbols.
  794. @example
  795. (parse-header 'accept-ranges "bytes")
  796. @result{} (bytes)
  797. @end example
  798. @end deftypevr
  799. @deftypevr {HTTP Header} UInt age
  800. The age of a cached response, in seconds.
  801. @example
  802. (parse-header 'age "3600")
  803. @result{} 3600
  804. @end example
  805. @end deftypevr
  806. @deftypevr {HTTP Header} ETag etag
  807. The entity-tag of the resource.
  808. @example
  809. (parse-header 'etag "\"foo\"")
  810. @result{} ("foo" . #t)
  811. @end example
  812. @end deftypevr
  813. @deftypevr {HTTP Header} URI location
  814. A URI on which a request may be completed. Used in combination with a
  815. redirecting status code to perform client-side redirection.
  816. @example
  817. (parse-header 'location "http://example.com/other")
  818. @result{} #<uri ...>
  819. @end example
  820. @end deftypevr
  821. @deftypevr {HTTP Header} List proxy-authenticate
  822. A list of challenges to a proxy, indicating the need for authentication.
  823. @example
  824. (parse-header 'proxy-authenticate "Basic realm=\"foo\"")
  825. @result{} ((basic (realm . "foo")))
  826. @end example
  827. @end deftypevr
  828. @deftypevr {HTTP Header} UInt|Date retry-after
  829. Used in combination with a server-busy status code, like 503, to
  830. indicate that a client should retry later. Either a number of seconds,
  831. or a date.
  832. @example
  833. (parse-header 'retry-after "60")
  834. @result{} 60
  835. @end example
  836. @end deftypevr
  837. @deftypevr {HTTP Header} String server
  838. A string identifying the server.
  839. @example
  840. (parse-header 'server "My first web server")
  841. @result{} "My first web server"
  842. @end example
  843. @end deftypevr
  844. @deftypevr {HTTP Header} *|List vary
  845. A set of request headers that were used in computing this response.
  846. Used to indicate that server-side content negotiation was performed, for
  847. example in response to the @code{accept-language} header. Can also be
  848. the symbol @code{*}, indicating that all headers were considered.
  849. @example
  850. (parse-header 'vary "Accept-Language, Accept")
  851. @result{} (accept-language accept)
  852. @end example
  853. @end deftypevr
  854. @deftypevr {HTTP Header} List www-authenticate
  855. A list of challenges to a user, indicating the need for authentication.
  856. @example
  857. (parse-header 'www-authenticate "Basic realm=\"foo\"")
  858. @result{} ((basic (realm . "foo")))
  859. @end example
  860. @end deftypevr
  861. @node Transfer Codings
  862. @subsection Transfer Codings
  863. HTTP 1.1 allows for various transfer codings to be applied to message
  864. bodies. These include various types of compression, and HTTP chunked
  865. encoding. Currently, only chunked encoding is supported by guile.
  866. Chunked coding is an optional coding that may be applied to message
  867. bodies, to allow messages whose length is not known beforehand to be
  868. returned. Such messages can be split into chunks, terminated by a final
  869. zero length chunk.
  870. In order to make dealing with encodings more simple, guile provides
  871. procedures to create ports that ``wrap'' existing ports, applying
  872. transformations transparently under the hood.
  873. These procedures are in the @code{(web http)} module.
  874. @example
  875. (use-modules (web http))
  876. @end example
  877. @deffn {Scheme Procedure} make-chunked-input-port port [#:keep-alive?=#f]
  878. Returns a new port, that transparently reads and decodes chunk-encoded
  879. data from @var{port}. If no more chunk-encoded data is available, it
  880. returns the end-of-file object. When the port is closed, @var{port} will
  881. also be closed, unless @var{keep-alive?} is true.
  882. @end deffn
  883. @example
  884. (use-modules (ice-9 rdelim))
  885. (define s "5\r\nFirst\r\nA\r\n line\n Sec\r\n8\r\nond line\r\n0\r\n")
  886. (define p (make-chunked-input-port (open-input-string s)))
  887. (read-line s)
  888. @result{} "First line"
  889. (read-line s)
  890. @result{} "Second line"
  891. @end example
  892. @deffn {Scheme Procedure} make-chunked-output-port port [#:keep-alive?=#f]
  893. Returns a new port, which transparently encodes data as chunk-encoded
  894. before writing it to @var{port}. Whenever a write occurs on this port,
  895. it buffers it, until the port is flushed, at which point it writes a
  896. chunk containing all the data written so far. When the port is closed,
  897. the data remaining is written to @var{port}, as is the terminating zero
  898. chunk. It also causes @var{port} to be closed, unless @var{keep-alive?}
  899. is true.
  900. Note. Forcing a chunked output port when there is no data is buffered
  901. does not write a zero chunk, as this would cause the data to be
  902. interpreted incorrectly by the client.
  903. @end deffn
  904. @example
  905. (call-with-output-string
  906. (lambda (out)
  907. (define out* (make-chunked-output-port out #:keep-alive? #t))
  908. (display "first chunk" out*)
  909. (force-output out*)
  910. (force-output out*) ; note this does not write a zero chunk
  911. (display "second chunk" out*)
  912. (close-port out*)))
  913. @result{} "b\r\nfirst chunk\r\nc\r\nsecond chunk\r\n0\r\n"
  914. @end example
  915. @node Requests
  916. @subsection HTTP Requests
  917. @example
  918. (use-modules (web request))
  919. @end example
  920. The request module contains a data type for HTTP requests.
  921. @subsubsection An Important Note on Character Sets
  922. HTTP requests consist of two parts: the request proper, consisting of a
  923. request line and a set of headers, and (optionally) a body. The body
  924. might have a binary content-type, and even in the textual case its
  925. length is specified in bytes, not characters.
  926. Therefore, HTTP is a fundamentally binary protocol. However the request
  927. line and headers are specified to be in a subset of ASCII, so they can
  928. be treated as text, provided that the port's encoding is set to an
  929. ASCII-compatible one-byte-per-character encoding. ISO-8859-1 (latin-1)
  930. is just such an encoding, and happens to be very efficient for Guile.
  931. So what Guile does when reading requests from the wire, or writing them
  932. out, is to set the port's encoding to latin-1, and treating the request
  933. headers as text.
  934. The request body is another issue. For binary data, the data is
  935. probably in a bytevector, so we use the R6RS binary output procedures to
  936. write out the binary payload. Textual data usually has to be written
  937. out to some character encoding, usually UTF-8, and then the resulting
  938. bytevector is written out to the port.
  939. In summary, Guile reads and writes HTTP over latin-1 sockets, without
  940. any loss of generality.
  941. @subsubsection Request API
  942. @deffn {Scheme Procedure} request? obj
  943. @deffnx {Scheme Procedure} request-method request
  944. @deffnx {Scheme Procedure} request-uri request
  945. @deffnx {Scheme Procedure} request-version request
  946. @deffnx {Scheme Procedure} request-headers request
  947. @deffnx {Scheme Procedure} request-meta request
  948. @deffnx {Scheme Procedure} request-port request
  949. A predicate and field accessors for the request type. The fields are as
  950. follows:
  951. @table @code
  952. @item method
  953. The HTTP method, for example, @code{GET}.
  954. @item uri
  955. The URI as a URI record.
  956. @item version
  957. The HTTP version pair, like @code{(1 . 1)}.
  958. @item headers
  959. The request headers, as an alist of parsed values.
  960. @item meta
  961. An arbitrary alist of other data, for example information returned in
  962. the @code{sockaddr} from @code{accept} (@pxref{Network Sockets and
  963. Communication}).
  964. @item port
  965. The port on which to read or write a request body, if any.
  966. @end table
  967. @end deffn
  968. @deffn {Scheme Procedure} read-request port [meta='()]
  969. Read an HTTP request from @var{port}, optionally attaching the given
  970. metadata, @var{meta}.
  971. As a side effect, sets the encoding on @var{port} to ISO-8859-1
  972. (latin-1), so that reading one character reads one byte. See the
  973. discussion of character sets above, for more information.
  974. Note that the body is not part of the request. Once you have read a
  975. request, you may read the body separately, and likewise for writing
  976. requests.
  977. @end deffn
  978. @deffn {Scheme Procedure} build-request uri [#:method='GET] @
  979. [#:version='(1 . 1)] [#:headers='()] [#:port=#f] [#:meta='()] @
  980. [#:validate-headers?=#t]
  981. Construct an HTTP request object. If @var{validate-headers?} is true,
  982. the headers are each run through their respective validators.
  983. @end deffn
  984. @deffn {Scheme Procedure} write-request r port
  985. Write the given HTTP request to @var{port}.
  986. Return a new request, whose @code{request-port} will continue writing
  987. on @var{port}, perhaps using some transfer encoding.
  988. @end deffn
  989. @deffn {Scheme Procedure} read-request-body r
  990. Reads the request body from @var{r}, as a bytevector. Return @code{#f}
  991. if there was no request body.
  992. @end deffn
  993. @deffn {Scheme Procedure} write-request-body r bv
  994. Write @var{bv}, a bytevector, to the port corresponding to the HTTP
  995. request @var{r}.
  996. @end deffn
  997. The various headers that are typically associated with HTTP requests may
  998. be accessed with these dedicated accessors. @xref{HTTP Headers}, for
  999. more information on the format of parsed headers.
  1000. @deffn {Scheme Procedure} request-accept request [default='()]
  1001. @deffnx {Scheme Procedure} request-accept-charset request [default='()]
  1002. @deffnx {Scheme Procedure} request-accept-encoding request [default='()]
  1003. @deffnx {Scheme Procedure} request-accept-language request [default='()]
  1004. @deffnx {Scheme Procedure} request-allow request [default='()]
  1005. @deffnx {Scheme Procedure} request-authorization request [default=#f]
  1006. @deffnx {Scheme Procedure} request-cache-control request [default='()]
  1007. @deffnx {Scheme Procedure} request-connection request [default='()]
  1008. @deffnx {Scheme Procedure} request-content-encoding request [default='()]
  1009. @deffnx {Scheme Procedure} request-content-language request [default='()]
  1010. @deffnx {Scheme Procedure} request-content-length request [default=#f]
  1011. @deffnx {Scheme Procedure} request-content-location request [default=#f]
  1012. @deffnx {Scheme Procedure} request-content-md5 request [default=#f]
  1013. @deffnx {Scheme Procedure} request-content-range request [default=#f]
  1014. @deffnx {Scheme Procedure} request-content-type request [default=#f]
  1015. @deffnx {Scheme Procedure} request-date request [default=#f]
  1016. @deffnx {Scheme Procedure} request-expect request [default='()]
  1017. @deffnx {Scheme Procedure} request-expires request [default=#f]
  1018. @deffnx {Scheme Procedure} request-from request [default=#f]
  1019. @deffnx {Scheme Procedure} request-host request [default=#f]
  1020. @deffnx {Scheme Procedure} request-if-match request [default=#f]
  1021. @deffnx {Scheme Procedure} request-if-modified-since request [default=#f]
  1022. @deffnx {Scheme Procedure} request-if-none-match request [default=#f]
  1023. @deffnx {Scheme Procedure} request-if-range request [default=#f]
  1024. @deffnx {Scheme Procedure} request-if-unmodified-since request [default=#f]
  1025. @deffnx {Scheme Procedure} request-last-modified request [default=#f]
  1026. @deffnx {Scheme Procedure} request-max-forwards request [default=#f]
  1027. @deffnx {Scheme Procedure} request-pragma request [default='()]
  1028. @deffnx {Scheme Procedure} request-proxy-authorization request [default=#f]
  1029. @deffnx {Scheme Procedure} request-range request [default=#f]
  1030. @deffnx {Scheme Procedure} request-referer request [default=#f]
  1031. @deffnx {Scheme Procedure} request-te request [default=#f]
  1032. @deffnx {Scheme Procedure} request-trailer request [default='()]
  1033. @deffnx {Scheme Procedure} request-transfer-encoding request [default='()]
  1034. @deffnx {Scheme Procedure} request-upgrade request [default='()]
  1035. @deffnx {Scheme Procedure} request-user-agent request [default=#f]
  1036. @deffnx {Scheme Procedure} request-via request [default='()]
  1037. @deffnx {Scheme Procedure} request-warning request [default='()]
  1038. Return the given request header, or @var{default} if none was present.
  1039. @end deffn
  1040. @deffn {Scheme Procedure} request-absolute-uri r [default-host=#f] [default-port=#f]
  1041. A helper routine to determine the absolute URI of a request, using the
  1042. @code{host} header and the default host and port.
  1043. @end deffn
  1044. @node Responses
  1045. @subsection HTTP Responses
  1046. @example
  1047. (use-modules (web response))
  1048. @end example
  1049. As with requests (@pxref{Requests}), Guile offers a data type for HTTP
  1050. responses. Again, the body is represented separately from the request.
  1051. @deffn {Scheme Procedure} response? obj
  1052. @deffnx {Scheme Procedure} response-version response
  1053. @deffnx {Scheme Procedure} response-code response
  1054. @deffnx {Scheme Procedure} response-reason-phrase response
  1055. @deffnx {Scheme Procedure} response-headers response
  1056. @deffnx {Scheme Procedure} response-port response
  1057. A predicate and field accessors for the response type. The fields are as
  1058. follows:
  1059. @table @code
  1060. @item version
  1061. The HTTP version pair, like @code{(1 . 1)}.
  1062. @item code
  1063. The HTTP response code, like @code{200}.
  1064. @item reason-phrase
  1065. The reason phrase, or the standard reason phrase for the response's
  1066. code.
  1067. @item headers
  1068. The response headers, as an alist of parsed values.
  1069. @item port
  1070. The port on which to read or write a response body, if any.
  1071. @end table
  1072. @end deffn
  1073. @deffn {Scheme Procedure} read-response port
  1074. Read an HTTP response from @var{port}.
  1075. As a side effect, sets the encoding on @var{port} to ISO-8859-1
  1076. (latin-1), so that reading one character reads one byte. See the
  1077. discussion of character sets in @ref{Responses}, for more information.
  1078. @end deffn
  1079. @deffn {Scheme Procedure} build-response [#:version='(1 . 1)] [#:code=200] [#:reason-phrase=#f] [#:headers='()] [#:port=#f] [#:validate-headers?=#t]
  1080. Construct an HTTP response object. If @var{validate-headers?} is true,
  1081. the headers are each run through their respective validators.
  1082. @end deffn
  1083. @deffn {Scheme Procedure} adapt-response-version response version
  1084. Adapt the given response to a different HTTP version. Return a new HTTP
  1085. response.
  1086. The idea is that many applications might just build a response for the
  1087. default HTTP version, and this method could handle a number of
  1088. programmatic transformations to respond to older HTTP versions (0.9 and
  1089. 1.0). But currently this function is a bit heavy-handed, just updating
  1090. the version field.
  1091. @end deffn
  1092. @deffn {Scheme Procedure} write-response r port
  1093. Write the given HTTP response to @var{port}.
  1094. Return a new response, whose @code{response-port} will continue writing
  1095. on @var{port}, perhaps using some transfer encoding.
  1096. @end deffn
  1097. @deffn {Scheme Procedure} response-must-not-include-body? r
  1098. Some responses, like those with status code 304, are specified as never
  1099. having bodies. This predicate returns @code{#t} for those responses.
  1100. Note also, though, that responses to @code{HEAD} requests must also not
  1101. have a body.
  1102. @end deffn
  1103. @deffn {Scheme Procedure} response-body-port r [#:decode?=#t] [#:keep-alive?=#t]
  1104. Return an input port from which the body of @var{r} can be read. The encoding
  1105. of the returned port is set according to @var{r}'s @code{content-type} header,
  1106. when it's textual, except if @var{decode?} is @code{#f}. Return @code{#f}
  1107. when no body is available.
  1108. When @var{keep-alive?} is @code{#f}, closing the returned port also closes
  1109. @var{r}'s response port.
  1110. @end deffn
  1111. @deffn {Scheme Procedure} read-response-body r
  1112. Read the response body from @var{r}, as a bytevector. Returns @code{#f}
  1113. if there was no response body.
  1114. @end deffn
  1115. @deffn {Scheme Procedure} write-response-body r bv
  1116. Write @var{bv}, a bytevector, to the port corresponding to the HTTP
  1117. response @var{r}.
  1118. @end deffn
  1119. As with requests, the various headers that are typically associated with
  1120. HTTP responses may be accessed with these dedicated accessors.
  1121. @xref{HTTP Headers}, for more information on the format of parsed
  1122. headers.
  1123. @deffn {Scheme Procedure} response-accept-ranges response [default=#f]
  1124. @deffnx {Scheme Procedure} response-age response [default='()]
  1125. @deffnx {Scheme Procedure} response-allow response [default='()]
  1126. @deffnx {Scheme Procedure} response-cache-control response [default='()]
  1127. @deffnx {Scheme Procedure} response-connection response [default='()]
  1128. @deffnx {Scheme Procedure} response-content-encoding response [default='()]
  1129. @deffnx {Scheme Procedure} response-content-language response [default='()]
  1130. @deffnx {Scheme Procedure} response-content-length response [default=#f]
  1131. @deffnx {Scheme Procedure} response-content-location response [default=#f]
  1132. @deffnx {Scheme Procedure} response-content-md5 response [default=#f]
  1133. @deffnx {Scheme Procedure} response-content-range response [default=#f]
  1134. @deffnx {Scheme Procedure} response-content-type response [default=#f]
  1135. @deffnx {Scheme Procedure} response-date response [default=#f]
  1136. @deffnx {Scheme Procedure} response-etag response [default=#f]
  1137. @deffnx {Scheme Procedure} response-expires response [default=#f]
  1138. @deffnx {Scheme Procedure} response-last-modified response [default=#f]
  1139. @deffnx {Scheme Procedure} response-location response [default=#f]
  1140. @deffnx {Scheme Procedure} response-pragma response [default='()]
  1141. @deffnx {Scheme Procedure} response-proxy-authenticate response [default=#f]
  1142. @deffnx {Scheme Procedure} response-retry-after response [default=#f]
  1143. @deffnx {Scheme Procedure} response-server response [default=#f]
  1144. @deffnx {Scheme Procedure} response-trailer response [default='()]
  1145. @deffnx {Scheme Procedure} response-transfer-encoding response [default='()]
  1146. @deffnx {Scheme Procedure} response-upgrade response [default='()]
  1147. @deffnx {Scheme Procedure} response-vary response [default='()]
  1148. @deffnx {Scheme Procedure} response-via response [default='()]
  1149. @deffnx {Scheme Procedure} response-warning response [default='()]
  1150. @deffnx {Scheme Procedure} response-www-authenticate response [default=#f]
  1151. Return the given response header, or @var{default} if none was present.
  1152. @end deffn
  1153. @deffn {Scheme Procedure} text-content-type? @var{type}
  1154. Return @code{#t} if @var{type}, a symbol as returned by
  1155. @code{response-content-type}, represents a textual type such as
  1156. @code{text/plain}.
  1157. @end deffn
  1158. @node Web Client
  1159. @subsection Web Client
  1160. @code{(web client)} provides a simple, synchronous HTTP client, built on
  1161. the lower-level HTTP, request, and response modules.
  1162. @example
  1163. (use-modules (web client))
  1164. @end example
  1165. @deffn {Scheme Procedure} open-socket-for-uri uri
  1166. Return an open input/output port for a connection to URI.
  1167. @end deffn
  1168. @deffn {Scheme Procedure} http-get uri arg...
  1169. @deffnx {Scheme Procedure} http-head uri arg...
  1170. @deffnx {Scheme Procedure} http-post uri arg...
  1171. @deffnx {Scheme Procedure} http-put uri arg...
  1172. @deffnx {Scheme Procedure} http-delete uri arg...
  1173. @deffnx {Scheme Procedure} http-trace uri arg...
  1174. @deffnx {Scheme Procedure} http-options uri arg...
  1175. Connect to the server corresponding to @var{uri} and make a request over
  1176. HTTP, using the appropriate method (@code{GET}, @code{HEAD}, etc.).
  1177. All of these procedures have the same prototype: a URI followed by an
  1178. optional sequence of keyword arguments. These keyword arguments allow
  1179. you to modify the requests in various ways, for example attaching a body
  1180. to the request, or setting specific headers. The following table lists
  1181. the keyword arguments and their default values.
  1182. @table @code
  1183. @item #:body #f
  1184. @item #:port (open-socket-for-uri @var{uri})]
  1185. @item #:version '(1 . 1)
  1186. @item #:keep-alive? #f
  1187. @item #:headers '()
  1188. @item #:decode-body? #t
  1189. @item #:streaming? #f
  1190. @end table
  1191. If you already have a port open, pass it as @var{port}. Otherwise, a
  1192. connection will be opened to the server corresponding to @var{uri}. Any
  1193. extra headers in the alist @var{headers} will be added to the request.
  1194. If @var{body} is not @code{#f}, a message body will also be sent with
  1195. the HTTP request. If @var{body} is a string, it is encoded according to
  1196. the content-type in @var{headers}, defaulting to UTF-8. Otherwise
  1197. @var{body} should be a bytevector, or @code{#f} for no body. Although a
  1198. message body may be sent with any request, usually only @code{POST} and
  1199. @code{PUT} requests have bodies.
  1200. If @var{decode-body?} is true, as is the default, the body of the
  1201. response will be decoded to string, if it is a textual content-type.
  1202. Otherwise it will be returned as a bytevector.
  1203. However, if @var{streaming?} is true, instead of eagerly reading the
  1204. response body from the server, this function only reads off the headers.
  1205. The response body will be returned as a port on which the data may be
  1206. read.
  1207. Unless @var{keep-alive?} is true, the port will be closed after the full
  1208. response body has been read.
  1209. Returns two values: the response read from the server, and the response
  1210. body as a string, bytevector, #f value, or as a port (if
  1211. @var{streaming?} is true).
  1212. @end deffn
  1213. @code{http-get} is useful for making one-off requests to web sites. If
  1214. you are writing a web spider or some other client that needs to handle a
  1215. number of requests in parallel, it's better to build an event-driven URL
  1216. fetcher, similar in structure to the web server (@pxref{Web Server}).
  1217. Another option, good but not as performant, would be to use threads,
  1218. possibly via par-map or futures.
  1219. @deffn {Scheme Parameter} current-http-proxy
  1220. Either @code{#f} or a non-empty string containing the URL of the HTTP
  1221. proxy server to be used by the procedures in the @code{(web client)}
  1222. module, including @code{open-socket-for-uri}. Its initial value is
  1223. based on the @env{http_proxy} environment variable.
  1224. @example
  1225. (current-http-proxy) @result{} "http://localhost:8123/"
  1226. (parameterize ((current-http-proxy #f))
  1227. (http-get "http://example.com/")) ; temporarily bypass proxy
  1228. (current-http-proxy) @result{} "http://localhost:8123/"
  1229. @end example
  1230. @end deffn
  1231. @node Web Server
  1232. @subsection Web Server
  1233. @code{(web server)} is a generic web server interface, along with a main
  1234. loop implementation for web servers controlled by Guile.
  1235. @example
  1236. (use-modules (web server))
  1237. @end example
  1238. The lowest layer is the @code{<server-impl>} object, which defines a set
  1239. of hooks to open a server, read a request from a client, write a
  1240. response to a client, and close a server. These hooks -- @code{open},
  1241. @code{read}, @code{write}, and @code{close}, respectively -- are bound
  1242. together in a @code{<server-impl>} object. Procedures in this module take a
  1243. @code{<server-impl>} object, if needed.
  1244. A @code{<server-impl>} may also be looked up by name. If you pass the
  1245. @code{http} symbol to @code{run-server}, Guile looks for a variable
  1246. named @code{http} in the @code{(web server http)} module, which should
  1247. be bound to a @code{<server-impl>} object. Such a binding is made by
  1248. instantiation of the @code{define-server-impl} syntax. In this way the
  1249. run-server loop can automatically load other backends if available.
  1250. The life cycle of a server goes as follows:
  1251. @enumerate
  1252. @item
  1253. The @code{open} hook is called, to open the server. @code{open} takes
  1254. zero or more arguments, depending on the backend, and returns an opaque
  1255. server socket object, or signals an error.
  1256. @item
  1257. The @code{read} hook is called, to read a request from a new client.
  1258. The @code{read} hook takes one argument, the server socket. It should
  1259. return three values: an opaque client socket, the request, and the
  1260. request body. The request should be a @code{<request>} object, from
  1261. @code{(web request)}. The body should be a string or a bytevector, or
  1262. @code{#f} if there is no body.
  1263. If the read failed, the @code{read} hook may return #f for the client
  1264. socket, request, and body.
  1265. @item
  1266. A user-provided handler procedure is called, with the request and body
  1267. as its arguments. The handler should return two values: the response,
  1268. as a @code{<response>} record from @code{(web response)}, and the
  1269. response body as bytevector, or @code{#f} if not present.
  1270. The respose and response body are run through @code{sanitize-response},
  1271. documented below. This allows the handler writer to take some
  1272. convenient shortcuts: for example, instead of a @code{<response>}, the
  1273. handler can simply return an alist of headers, in which case a default
  1274. response object is constructed with those headers. Instead of a
  1275. bytevector for the body, the handler can return a string, which will be
  1276. serialized into an appropriate encoding; or it can return a procedure,
  1277. which will be called on a port to write out the data. See the
  1278. @code{sanitize-response} documentation, for more.
  1279. @item
  1280. The @code{write} hook is called with three arguments: the client
  1281. socket, the response, and the body. The @code{write} hook returns no
  1282. values.
  1283. @item
  1284. At this point the request handling is complete. For a loop, we
  1285. loop back and try to read a new request.
  1286. @item
  1287. If the user interrupts the loop, the @code{close} hook is called on
  1288. the server socket.
  1289. @end enumerate
  1290. A user may define a server implementation with the following form:
  1291. @deffn {Scheme Syntax} define-server-impl name open read write close
  1292. Make a @code{<server-impl>} object with the hooks @var{open},
  1293. @var{read}, @var{write}, and @var{close}, and bind it to the symbol
  1294. @var{name} in the current module.
  1295. @end deffn
  1296. @deffn {Scheme Procedure} lookup-server-impl impl
  1297. Look up a server implementation. If @var{impl} is a server
  1298. implementation already, it is returned directly. If it is a symbol, the
  1299. binding named @var{impl} in the @code{(web server @var{impl})} module is
  1300. looked up. Otherwise an error is signaled.
  1301. Currently a server implementation is a somewhat opaque type, useful only
  1302. for passing to other procedures in this module, like @code{read-client}.
  1303. @end deffn
  1304. The @code{(web server)} module defines a number of routines that use
  1305. @code{<server-impl>} objects to implement parts of a web server. Given
  1306. that we don't expose the accessors for the various fields of a
  1307. @code{<server-impl>}, indeed these routines are the only procedures with
  1308. any access to the impl objects.
  1309. @deffn {Scheme Procedure} open-server impl open-params
  1310. Open a server for the given implementation. Return one value, the new
  1311. server object. The implementation's @code{open} procedure is applied to
  1312. @var{open-params}, which should be a list.
  1313. @end deffn
  1314. @deffn {Scheme Procedure} read-client impl server
  1315. Read a new client from @var{server}, by applying the implementation's
  1316. @code{read} procedure to the server. If successful, return three
  1317. values: an object corresponding to the client, a request object, and the
  1318. request body. If any exception occurs, return @code{#f} for all three
  1319. values.
  1320. @end deffn
  1321. @deffn {Scheme Procedure} handle-request handler request body state
  1322. Handle a given request, returning the response and body.
  1323. The response and response body are produced by calling the given
  1324. @var{handler} with @var{request} and @var{body} as arguments.
  1325. The elements of @var{state} are also passed to @var{handler} as
  1326. arguments, and may be returned as additional values. The new
  1327. @var{state}, collected from the @var{handler}'s return values, is then
  1328. returned as a list. The idea is that a server loop receives a handler
  1329. from the user, along with whatever state values the user is interested
  1330. in, allowing the user's handler to explicitly manage its state.
  1331. @end deffn
  1332. @deffn {Scheme Procedure} sanitize-response request response body
  1333. ``Sanitize'' the given response and body, making them appropriate for
  1334. the given request.
  1335. As a convenience to web handler authors, @var{response} may be given as
  1336. an alist of headers, in which case it is used to construct a default
  1337. response. Ensures that the response version corresponds to the request
  1338. version. If @var{body} is a string, encodes the string to a bytevector,
  1339. in an encoding appropriate for @var{response}. Adds a
  1340. @code{content-length} and @code{content-type} header, as necessary.
  1341. If @var{body} is a procedure, it is called with a port as an argument,
  1342. and the output collected as a bytevector. In the future we might try to
  1343. instead use a compressing, chunk-encoded port, and call this procedure
  1344. later, in the write-client procedure. Authors are advised not to rely on
  1345. the procedure being called at any particular time.
  1346. @end deffn
  1347. @deffn {Scheme Procedure} write-client impl server client response body
  1348. Write an HTTP response and body to @var{client}. If the server and
  1349. client support persistent connections, it is the implementation's
  1350. responsibility to keep track of the client thereafter, presumably by
  1351. attaching it to the @var{server} argument somehow.
  1352. @end deffn
  1353. @deffn {Scheme Procedure} close-server impl server
  1354. Release resources allocated by a previous invocation of
  1355. @code{open-server}.
  1356. @end deffn
  1357. Given the procedures above, it is a small matter to make a web server:
  1358. @deffn {Scheme Procedure} serve-one-client handler impl server state
  1359. Read one request from @var{server}, call @var{handler} on the request
  1360. and body, and write the response to the client. Return the new state
  1361. produced by the handler procedure.
  1362. @end deffn
  1363. @deffn {Scheme Procedure} run-server handler @
  1364. [impl='http] [open-params='()] @
  1365. arg @dots{}
  1366. Run Guile's built-in web server.
  1367. @var{handler} should be a procedure that takes two or more arguments,
  1368. the HTTP request and request body, and returns two or more values, the
  1369. response and response body.
  1370. For examples, skip ahead to the next section, @ref{Web Examples}.
  1371. The response and body will be run through @code{sanitize-response}
  1372. before sending back to the client.
  1373. Additional arguments to @var{handler} are taken from @var{arg}
  1374. @enddots{}. These arguments comprise a @dfn{state}. Additional return
  1375. values are accumulated into a new state, which will be used for
  1376. subsequent requests. In this way a handler can explicitly manage its
  1377. state.
  1378. @end deffn
  1379. The default web server implementation is @code{http}, which binds to a
  1380. socket, listening for request on that port.
  1381. @deffn {HTTP Implementation} http [#:host=#f] @
  1382. [#:family=AF_INET] @
  1383. [#:addr=INADDR_LOOPBACK] @
  1384. [#:port 8080] [#:socket]
  1385. The default HTTP implementation. We document it as a function with
  1386. keyword arguments, because that is precisely the way that it is -- all
  1387. of the @var{open-params} to @code{run-server} get passed to the
  1388. implementation's open function.
  1389. @example
  1390. ;; The defaults: localhost:8080
  1391. (run-server handler)
  1392. ;; Same thing
  1393. (run-server handler 'http '())
  1394. ;; On a different port
  1395. (run-server handler 'http '(#:port 8081))
  1396. ;; IPv6
  1397. (run-server handler 'http '(#:family AF_INET6 #:port 8081))
  1398. ;; Custom socket
  1399. (run-server handler 'http `(#:socket ,(sudo-make-me-a-socket)))
  1400. @end example
  1401. @end deffn
  1402. @node Web Examples
  1403. @subsection Web Examples
  1404. Well, enough about the tedious internals. Let's make a web application!
  1405. @subsubsection Hello, World!
  1406. The first program we have to write, of course, is ``Hello, World!''.
  1407. This means that we have to implement a web handler that does what we
  1408. want.
  1409. Now we define a handler, a function of two arguments and two return
  1410. values:
  1411. @example
  1412. (define (handler request request-body)
  1413. (values @var{response} @var{response-body}))
  1414. @end example
  1415. In this first example, we take advantage of a short-cut, returning an
  1416. alist of headers instead of a proper response object. The response body
  1417. is our payload:
  1418. @example
  1419. (define (hello-world-handler request request-body)
  1420. (values '((content-type . (text/plain)))
  1421. "Hello World!"))
  1422. @end example
  1423. Now let's test it, by running a server with this handler. Load up the
  1424. web server module if you haven't yet done so, and run a server with this
  1425. handler:
  1426. @example
  1427. (use-modules (web server))
  1428. (run-server hello-world-handler)
  1429. @end example
  1430. By default, the web server listens for requests on
  1431. @code{localhost:8080}. Visit that address in your web browser to
  1432. test. If you see the string, @code{Hello World!}, sweet!
  1433. @subsubsection Inspecting the Request
  1434. The Hello World program above is a general greeter, responding to all
  1435. URIs. To make a more exclusive greeter, we need to inspect the request
  1436. object, and conditionally produce different results. So let's load up
  1437. the request, response, and URI modules, and do just that.
  1438. @example
  1439. (use-modules (web server)) ; you probably did this already
  1440. (use-modules (web request)
  1441. (web response)
  1442. (web uri))
  1443. (define (request-path-components request)
  1444. (split-and-decode-uri-path (uri-path (request-uri request))))
  1445. (define (hello-hacker-handler request body)
  1446. (if (equal? (request-path-components request)
  1447. '("hacker"))
  1448. (values '((content-type . (text/plain)))
  1449. "Hello hacker!")
  1450. (not-found request)))
  1451. (run-server hello-hacker-handler)
  1452. @end example
  1453. Here we see that we have defined a helper to return the components of
  1454. the URI path as a list of strings, and used that to check for a request
  1455. to @code{/hacker/}. Then the success case is just as before -- visit
  1456. @code{http://localhost:8080/hacker/} in your browser to check.
  1457. You should always match against URI path components as decoded by
  1458. @code{split-and-decode-uri-path}. The above example will work for
  1459. @code{/hacker/}, @code{//hacker///}, and @code{/h%61ck%65r}.
  1460. But we forgot to define @code{not-found}! If you are pasting these
  1461. examples into a REPL, accessing any other URI in your web browser will
  1462. drop your Guile console into the debugger:
  1463. @example
  1464. <unnamed port>:38:7: In procedure module-lookup:
  1465. <unnamed port>:38:7: Unbound variable: not-found
  1466. Entering a new prompt. Type `,bt' for a backtrace or `,q' to continue.
  1467. scheme@@(guile-user) [1]>
  1468. @end example
  1469. So let's define the function, right there in the debugger. As you
  1470. probably know, we'll want to return a 404 response.
  1471. @example
  1472. ;; Paste this in your REPL
  1473. (define (not-found request)
  1474. (values (build-response #:code 404)
  1475. (string-append "Resource not found: "
  1476. (uri->string (request-uri request)))))
  1477. ;; Now paste this to let the web server keep going:
  1478. ,continue
  1479. @end example
  1480. Now if you access @code{http://localhost/foo/}, you get this error
  1481. message. (Note that some popular web browsers won't show
  1482. server-generated 404 messages, showing their own instead, unless the 404
  1483. message body is long enough.)
  1484. @subsubsection Higher-Level Interfaces
  1485. The web handler interface is a common baseline that all kinds of Guile
  1486. web applications can use. You will usually want to build something on
  1487. top of it, however, especially when producing HTML. Here is a simple
  1488. example that builds up HTML output using SXML (@pxref{SXML}).
  1489. First, load up the modules:
  1490. @example
  1491. (use-modules (web server)
  1492. (web request)
  1493. (web response)
  1494. (sxml simple))
  1495. @end example
  1496. Now we define a simple templating function that takes a list of HTML
  1497. body elements, as SXML, and puts them in our super template:
  1498. @example
  1499. (define (templatize title body)
  1500. `(html (head (title ,title))
  1501. (body ,@@body)))
  1502. @end example
  1503. For example, the simplest Hello HTML can be produced like this:
  1504. @example
  1505. (sxml->xml (templatize "Hello!" '((b "Hi!"))))
  1506. @print{}
  1507. <html><head><title>Hello!</title></head><body><b>Hi!</b></body></html>
  1508. @end example
  1509. Much better to work with Scheme data types than to work with HTML as
  1510. strings. Now we define a little response helper:
  1511. @example
  1512. (define* (respond #:optional body #:key
  1513. (status 200)
  1514. (title "Hello hello!")
  1515. (doctype "<!DOCTYPE html>\n")
  1516. (content-type-params '((charset . "utf-8")))
  1517. (content-type 'text/html)
  1518. (extra-headers '())
  1519. (sxml (and body (templatize title body))))
  1520. (values (build-response
  1521. #:code status
  1522. #:headers `((content-type
  1523. . (,content-type ,@@content-type-params))
  1524. ,@@extra-headers))
  1525. (lambda (port)
  1526. (if sxml
  1527. (begin
  1528. (if doctype (display doctype port))
  1529. (sxml->xml sxml port))))))
  1530. @end example
  1531. Here we see the power of keyword arguments with default initializers. By
  1532. the time the arguments are fully parsed, the @code{sxml} local variable
  1533. will hold the templated SXML, ready for sending out to the client.
  1534. Also, instead of returning the body as a string, @code{respond} gives a
  1535. procedure, which will be called by the web server to write out the
  1536. response to the client.
  1537. Now, a simple example using this responder, which lays out the incoming
  1538. headers in an HTML table.
  1539. @example
  1540. (define (debug-page request body)
  1541. (respond
  1542. `((h1 "hello world!")
  1543. (table
  1544. (tr (th "header") (th "value"))
  1545. ,@@(map (lambda (pair)
  1546. `(tr (td (tt ,(with-output-to-string
  1547. (lambda () (display (car pair))))))
  1548. (td (tt ,(with-output-to-string
  1549. (lambda ()
  1550. (write (cdr pair))))))))
  1551. (request-headers request))))))
  1552. (run-server debug-page)
  1553. @end example
  1554. Now if you visit any local address in your web browser, we actually see
  1555. some HTML, finally.
  1556. @subsubsection Conclusion
  1557. Well, this is about as far as Guile's built-in web support goes, for
  1558. now. There are many ways to make a web application, but hopefully by
  1559. standardizing the most fundamental data types, users will be able to
  1560. choose the approach that suits them best, while also being able to
  1561. switch between implementations of the server. This is a relatively new
  1562. part of Guile, so if you have feedback, let us know, and we can take it
  1563. into account. Happy hacking on the web!
  1564. @c Local Variables:
  1565. @c TeX-master: "guile.texi"
  1566. @c End: