index.html 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. <!--{
  2. "Title": "Writing Web Applications",
  3. "Template": true
  4. }-->
  5. <h2>Introduction</h2>
  6. <p>
  7. Covered in this tutorial:
  8. </p>
  9. <ul>
  10. <li>Creating a data structure with load and save methods</li>
  11. <li>Using the <code>net/http</code> package to build web applications
  12. <li>Using the <code>html/template</code> package to process HTML templates</li>
  13. <li>Using the <code>regexp</code> package to validate user input</li>
  14. <li>Using closures</li>
  15. </ul>
  16. <p>
  17. Assumed knowledge:
  18. </p>
  19. <ul>
  20. <li>Programming experience</li>
  21. <li>Understanding of basic web technologies (HTTP, HTML)</li>
  22. <li>Some UNIX/DOS command-line knowledge</li>
  23. </ul>
  24. <h2>Getting Started</h2>
  25. <p>
  26. At present, you need to have a FreeBSD, Linux, OS X, or Windows machine to run Go.
  27. We will use <code>$</code> to represent the command prompt.
  28. </p>
  29. <p>
  30. Install Go (see the <a href="/doc/install">Installation Instructions</a>).
  31. </p>
  32. <p>
  33. Make a new directory for this tutorial inside your <code>GOPATH</code> and cd to it:
  34. </p>
  35. <pre>
  36. $ mkdir gowiki
  37. $ cd gowiki
  38. </pre>
  39. <p>
  40. Create a file named <code>wiki.go</code>, open it in your favorite editor, and
  41. add the following lines:
  42. </p>
  43. <pre>
  44. package main
  45. import (
  46. "fmt"
  47. "io/ioutil"
  48. )
  49. </pre>
  50. <p>
  51. We import the <code>fmt</code> and <code>ioutil</code> packages from the Go
  52. standard library. Later, as we implement additional functionality, we will
  53. add more packages to this <code>import</code> declaration.
  54. </p>
  55. <h2>Data Structures</h2>
  56. <p>
  57. Let's start by defining the data structures. A wiki consists of a series of
  58. interconnected pages, each of which has a title and a body (the page content).
  59. Here, we define <code>Page</code> as a struct with two fields representing
  60. the title and body.
  61. </p>
  62. {{code "doc/articles/wiki/part1.go" `/^type Page/` `/}/`}}
  63. <p>
  64. The type <code>[]byte</code> means "a <code>byte</code> slice".
  65. (See <a href="/doc/articles/slices_usage_and_internals.html">Slices: usage and
  66. internals</a> for more on slices.)
  67. The <code>Body</code> element is a <code>[]byte</code> rather than
  68. <code>string</code> because that is the type expected by the <code>io</code>
  69. libraries we will use, as you'll see below.
  70. </p>
  71. <p>
  72. The <code>Page</code> struct describes how page data will be stored in memory.
  73. But what about persistent storage? We can address that by creating a
  74. <code>save</code> method on <code>Page</code>:
  75. </p>
  76. {{code "doc/articles/wiki/part1.go" `/^func.*Page.*save/` `/}/`}}
  77. <p>
  78. This method's signature reads: "This is a method named <code>save</code> that
  79. takes as its receiver <code>p</code>, a pointer to <code>Page</code> . It takes
  80. no parameters, and returns a value of type <code>error</code>."
  81. </p>
  82. <p>
  83. This method will save the <code>Page</code>'s <code>Body</code> to a text
  84. file. For simplicity, we will use the <code>Title</code> as the file name.
  85. </p>
  86. <p>
  87. The <code>save</code> method returns an <code>error</code> value because
  88. that is the return type of <code>WriteFile</code> (a standard library function
  89. that writes a byte slice to a file). The <code>save</code> method returns the
  90. error value, to let the application handle it should anything go wrong while
  91. writing the file. If all goes well, <code>Page.save()</code> will return
  92. <code>nil</code> (the zero-value for pointers, interfaces, and some other
  93. types).
  94. </p>
  95. <p>
  96. The octal integer literal <code>0600</code>, passed as the third parameter to
  97. <code>WriteFile</code>, indicates that the file should be created with
  98. read-write permissions for the current user only. (See the Unix man page
  99. <code>open(2)</code> for details.)
  100. </p>
  101. <p>
  102. In addition to saving pages, we will want to load pages, too:
  103. </p>
  104. {{code "doc/articles/wiki/part1-noerror.go" `/^func loadPage/` `/^}/`}}
  105. <p>
  106. The function <code>loadPage</code> constructs the file name from the title
  107. parameter, reads the file's contents into a new variable <code>body</code>, and
  108. returns a pointer to a <code>Page</code> literal constructed with the proper
  109. title and body values.
  110. </p>
  111. <p>
  112. Functions can return multiple values. The standard library function
  113. <code>io.ReadFile</code> returns <code>[]byte</code> and <code>error</code>.
  114. In <code>loadPage</code>, error isn't being handled yet; the "blank identifier"
  115. represented by the underscore (<code>_</code>) symbol is used to throw away the
  116. error return value (in essence, assigning the value to nothing).
  117. </p>
  118. <p>
  119. But what happens if <code>ReadFile</code> encounters an error? For example,
  120. the file might not exist. We should not ignore such errors. Let's modify the
  121. function to return <code>*Page</code> and <code>error</code>.
  122. </p>
  123. {{code "doc/articles/wiki/part1.go" `/^func loadPage/` `/^}/`}}
  124. <p>
  125. Callers of this function can now check the second parameter; if it is
  126. <code>nil</code> then it has successfully loaded a Page. If not, it will be an
  127. <code>error</code> that can be handled by the caller (see the
  128. <a href="/ref/spec#Errors">language specification</a> for details).
  129. </p>
  130. <p>
  131. At this point we have a simple data structure and the ability to save to and
  132. load from a file. Let's write a <code>main</code> function to test what we've
  133. written:
  134. </p>
  135. {{code "doc/articles/wiki/part1.go" `/^func main/` `/^}/`}}
  136. <p>
  137. After compiling and executing this code, a file named <code>TestPage.txt</code>
  138. would be created, containing the contents of <code>p1</code>. The file would
  139. then be read into the struct <code>p2</code>, and its <code>Body</code> element
  140. printed to the screen.
  141. </p>
  142. <p>
  143. You can compile and run the program like this:
  144. </p>
  145. <pre>
  146. $ go build wiki.go
  147. $ ./wiki
  148. This is a sample Page.
  149. </pre>
  150. <p>
  151. (If you're using Windows you must type "<code>wiki</code>" without the
  152. "<code>./</code>" to run the program.)
  153. </p>
  154. <p>
  155. <a href="part1.go">Click here to view the code we've written so far.</a>
  156. </p>
  157. <h2>Introducing the <code>net/http</code> package (an interlude)</h2>
  158. <p>
  159. Here's a full working example of a simple web server:
  160. </p>
  161. {{code "doc/articles/wiki/http-sample.go"}}
  162. <p>
  163. The <code>main</code> function begins with a call to
  164. <code>http.HandleFunc</code>, which tells the <code>http</code> package to
  165. handle all requests to the web root (<code>"/"</code>) with
  166. <code>handler</code>.
  167. </p>
  168. <p>
  169. It then calls <code>http.ListenAndServe</code>, specifying that it should
  170. listen on port 8080 on any interface (<code>":8080"</code>). (Don't
  171. worry about its second parameter, <code>nil</code>, for now.)
  172. This function will block until the program is terminated.
  173. </p>
  174. <p>
  175. <code>ListenAndServe</code> always returns an error, since it only returns when an
  176. unexpected error occurs.
  177. In order to log that error we wrap the function call with <code>log.Fatal</code>.
  178. </p>
  179. <p>
  180. The function <code>handler</code> is of the type <code>http.HandlerFunc</code>.
  181. It takes an <code>http.ResponseWriter</code> and an <code>http.Request</code> as
  182. its arguments.
  183. </p>
  184. <p>
  185. An <code>http.ResponseWriter</code> value assembles the HTTP server's response; by writing
  186. to it, we send data to the HTTP client.
  187. </p>
  188. <p>
  189. An <code>http.Request</code> is a data structure that represents the client
  190. HTTP request. <code>r.URL.Path</code> is the path component
  191. of the request URL. The trailing <code>[1:]</code> means
  192. "create a sub-slice of <code>Path</code> from the 1st character to the end."
  193. This drops the leading "/" from the path name.
  194. </p>
  195. <p>
  196. If you run this program and access the URL:
  197. </p>
  198. <pre>http://localhost:8080/monkeys</pre>
  199. <p>
  200. the program would present a page containing:
  201. </p>
  202. <pre>Hi there, I love monkeys!</pre>
  203. <h2>Using <code>net/http</code> to serve wiki pages</h2>
  204. <p>
  205. To use the <code>net/http</code> package, it must be imported:
  206. </p>
  207. <pre>
  208. import (
  209. "fmt"
  210. "io/ioutil"
  211. <b>"net/http"</b>
  212. )
  213. </pre>
  214. <p>
  215. Let's create a handler, <code>viewHandler</code> that will allow users to
  216. view a wiki page. It will handle URLs prefixed with "/view/".
  217. </p>
  218. {{code "doc/articles/wiki/part2.go" `/^func viewHandler/` `/^}/`}}
  219. <p>
  220. Again, note the use of <code>_</code> to ignore the <code>error</code>
  221. return value from <code>loadPage</code>. This is done here for simplicity
  222. and generally considered bad practice. We will attend to this later.
  223. </p>
  224. <p>
  225. First, this function extracts the page title from <code>r.URL.Path</code>,
  226. the path component of the request URL.
  227. The <code>Path</code> is re-sliced with <code>[len("/view/"):]</code> to drop
  228. the leading <code>"/view/"</code> component of the request path.
  229. This is because the path will invariably begin with <code>"/view/"</code>,
  230. which is not part of the page's title.
  231. </p>
  232. <p>
  233. The function then loads the page data, formats the page with a string of simple
  234. HTML, and writes it to <code>w</code>, the <code>http.ResponseWriter</code>.
  235. </p>
  236. <p>
  237. To use this handler, we rewrite our <code>main</code> function to
  238. initialize <code>http</code> using the <code>viewHandler</code> to handle
  239. any requests under the path <code>/view/</code>.
  240. </p>
  241. {{code "doc/articles/wiki/part2.go" `/^func main/` `/^}/`}}
  242. <p>
  243. <a href="part2.go">Click here to view the code we've written so far.</a>
  244. </p>
  245. <p>
  246. Let's create some page data (as <code>test.txt</code>), compile our code, and
  247. try serving a wiki page.
  248. </p>
  249. <p>
  250. Open <code>test.txt</code> file in your editor, and save the string "Hello world" (without quotes)
  251. in it.
  252. </p>
  253. <pre>
  254. $ go build wiki.go
  255. $ ./wiki
  256. </pre>
  257. <p>
  258. (If you're using Windows you must type "<code>wiki</code>" without the
  259. "<code>./</code>" to run the program.)
  260. </p>
  261. <p>
  262. With this web server running, a visit to <code><a
  263. href="http://localhost:8080/view/test">http://localhost:8080/view/test</a></code>
  264. should show a page titled "test" containing the words "Hello world".
  265. </p>
  266. <h2>Editing Pages</h2>
  267. <p>
  268. A wiki is not a wiki without the ability to edit pages. Let's create two new
  269. handlers: one named <code>editHandler</code> to display an 'edit page' form,
  270. and the other named <code>saveHandler</code> to save the data entered via the
  271. form.
  272. </p>
  273. <p>
  274. First, we add them to <code>main()</code>:
  275. </p>
  276. {{code "doc/articles/wiki/final-noclosure.go" `/^func main/` `/^}/`}}
  277. <p>
  278. The function <code>editHandler</code> loads the page
  279. (or, if it doesn't exist, create an empty <code>Page</code> struct),
  280. and displays an HTML form.
  281. </p>
  282. {{code "doc/articles/wiki/notemplate.go" `/^func editHandler/` `/^}/`}}
  283. <p>
  284. This function will work fine, but all that hard-coded HTML is ugly.
  285. Of course, there is a better way.
  286. </p>
  287. <h2>The <code>html/template</code> package</h2>
  288. <p>
  289. The <code>html/template</code> package is part of the Go standard library.
  290. We can use <code>html/template</code> to keep the HTML in a separate file,
  291. allowing us to change the layout of our edit page without modifying the
  292. underlying Go code.
  293. </p>
  294. <p>
  295. First, we must add <code>html/template</code> to the list of imports. We
  296. also won't be using <code>fmt</code> anymore, so we have to remove that.
  297. </p>
  298. <pre>
  299. import (
  300. <b>"html/template"</b>
  301. "io/ioutil"
  302. "net/http"
  303. )
  304. </pre>
  305. <p>
  306. Let's create a template file containing the HTML form.
  307. Open a new file named <code>edit.html</code>, and add the following lines:
  308. </p>
  309. {{code "doc/articles/wiki/edit.html"}}
  310. <p>
  311. Modify <code>editHandler</code> to use the template, instead of the hard-coded
  312. HTML:
  313. </p>
  314. {{code "doc/articles/wiki/final-noerror.go" `/^func editHandler/` `/^}/`}}
  315. <p>
  316. The function <code>template.ParseFiles</code> will read the contents of
  317. <code>edit.html</code> and return a <code>*template.Template</code>.
  318. </p>
  319. <p>
  320. The method <code>t.Execute</code> executes the template, writing the
  321. generated HTML to the <code>http.ResponseWriter</code>.
  322. The <code>.Title</code> and <code>.Body</code> dotted identifiers refer to
  323. <code>p.Title</code> and <code>p.Body</code>.
  324. </p>
  325. <p>
  326. Template directives are enclosed in double curly braces.
  327. The <code>printf "%s" .Body</code> instruction is a function call
  328. that outputs <code>.Body</code> as a string instead of a stream of bytes,
  329. the same as a call to <code>fmt.Printf</code>.
  330. The <code>html/template</code> package helps guarantee that only safe and
  331. correct-looking HTML is generated by template actions. For instance, it
  332. automatically escapes any greater than sign (<code>&gt;</code>), replacing it
  333. with <code>&amp;gt;</code>, to make sure user data does not corrupt the form
  334. HTML.
  335. </p>
  336. <p>
  337. Since we're working with templates now, let's create a template for our
  338. <code>viewHandler</code> called <code>view.html</code>:
  339. </p>
  340. {{code "doc/articles/wiki/view.html"}}
  341. <p>
  342. Modify <code>viewHandler</code> accordingly:
  343. </p>
  344. {{code "doc/articles/wiki/final-noerror.go" `/^func viewHandler/` `/^}/`}}
  345. <p>
  346. Notice that we've used almost exactly the same templating code in both
  347. handlers. Let's remove this duplication by moving the templating code
  348. to its own function:
  349. </p>
  350. {{code "doc/articles/wiki/final-template.go" `/^func renderTemplate/` `/^}/`}}
  351. <p>
  352. And modify the handlers to use that function:
  353. </p>
  354. {{code "doc/articles/wiki/final-template.go" `/^func viewHandler/` `/^}/`}}
  355. {{code "doc/articles/wiki/final-template.go" `/^func editHandler/` `/^}/`}}
  356. <p>
  357. If we comment out the registration of our unimplemented save handler in
  358. <code>main</code>, we can once again build and test our program.
  359. <a href="part3.go">Click here to view the code we've written so far.</a>
  360. </p>
  361. <h2>Handling non-existent pages</h2>
  362. <p>
  363. What if you visit <a href="http://localhost:8080/view/APageThatDoesntExist">
  364. <code>/view/APageThatDoesntExist</code></a>? You'll see a page containing
  365. HTML. This is because it ignores the error return value from
  366. <code>loadPage</code> and continues to try and fill out the template
  367. with no data. Instead, if the requested Page doesn't exist, it should
  368. redirect the client to the edit Page so the content may be created:
  369. </p>
  370. {{code "doc/articles/wiki/part3-errorhandling.go" `/^func viewHandler/` `/^}/`}}
  371. <p>
  372. The <code>http.Redirect</code> function adds an HTTP status code of
  373. <code>http.StatusFound</code> (302) and a <code>Location</code>
  374. header to the HTTP response.
  375. </p>
  376. <h2>Saving Pages</h2>
  377. <p>
  378. The function <code>saveHandler</code> will handle the submission of forms
  379. located on the edit pages. After uncommenting the related line in
  380. <code>main</code>, let's implement the handler:
  381. </p>
  382. {{code "doc/articles/wiki/final-template.go" `/^func saveHandler/` `/^}/`}}
  383. <p>
  384. The page title (provided in the URL) and the form's only field,
  385. <code>Body</code>, are stored in a new <code>Page</code>.
  386. The <code>save()</code> method is then called to write the data to a file,
  387. and the client is redirected to the <code>/view/</code> page.
  388. </p>
  389. <p>
  390. The value returned by <code>FormValue</code> is of type <code>string</code>.
  391. We must convert that value to <code>[]byte</code> before it will fit into
  392. the <code>Page</code> struct. We use <code>[]byte(body)</code> to perform
  393. the conversion.
  394. </p>
  395. <h2>Error handling</h2>
  396. <p>
  397. There are several places in our program where errors are being ignored. This
  398. is bad practice, not least because when an error does occur the program will
  399. have unintended behavior. A better solution is to handle the errors and return
  400. an error message to the user. That way if something does go wrong, the server
  401. will function exactly how we want and the user can be notified.
  402. </p>
  403. <p>
  404. First, let's handle the errors in <code>renderTemplate</code>:
  405. </p>
  406. {{code "doc/articles/wiki/final-parsetemplate.go" `/^func renderTemplate/` `/^}/`}}
  407. <p>
  408. The <code>http.Error</code> function sends a specified HTTP response code
  409. (in this case "Internal Server Error") and error message.
  410. Already the decision to put this in a separate function is paying off.
  411. </p>
  412. <p>
  413. Now let's fix up <code>saveHandler</code>:
  414. </p>
  415. {{code "doc/articles/wiki/part3-errorhandling.go" `/^func saveHandler/` `/^}/`}}
  416. <p>
  417. Any errors that occur during <code>p.save()</code> will be reported
  418. to the user.
  419. </p>
  420. <h2>Template caching</h2>
  421. <p>
  422. There is an inefficiency in this code: <code>renderTemplate</code> calls
  423. <code>ParseFiles</code> every time a page is rendered.
  424. A better approach would be to call <code>ParseFiles</code> once at program
  425. initialization, parsing all templates into a single <code>*Template</code>.
  426. Then we can use the
  427. <a href="/pkg/html/template/#Template.ExecuteTemplate"><code>ExecuteTemplate</code></a>
  428. method to render a specific template.
  429. </p>
  430. <p>
  431. First we create a global variable named <code>templates</code>, and initialize
  432. it with <code>ParseFiles</code>.
  433. </p>
  434. {{code "doc/articles/wiki/final.go" `/var templates/`}}
  435. <p>
  436. The function <code>template.Must</code> is a convenience wrapper that panics
  437. when passed a non-nil <code>error</code> value, and otherwise returns the
  438. <code>*Template</code> unaltered. A panic is appropriate here; if the templates
  439. can't be loaded the only sensible thing to do is exit the program.
  440. </p>
  441. <p>
  442. The <code>ParseFiles</code> function takes any number of string arguments that
  443. identify our template files, and parses those files into templates that are
  444. named after the base file name. If we were to add more templates to our
  445. program, we would add their names to the <code>ParseFiles</code> call's
  446. arguments.
  447. </p>
  448. <p>
  449. We then modify the <code>renderTemplate</code> function to call the
  450. <code>templates.ExecuteTemplate</code> method with the name of the appropriate
  451. template:
  452. </p>
  453. {{code "doc/articles/wiki/final.go" `/func renderTemplate/` `/^}/`}}
  454. <p>
  455. Note that the template name is the template file name, so we must
  456. append <code>".html"</code> to the <code>tmpl</code> argument.
  457. </p>
  458. <h2>Validation</h2>
  459. <p>
  460. As you may have observed, this program has a serious security flaw: a user
  461. can supply an arbitrary path to be read/written on the server. To mitigate
  462. this, we can write a function to validate the title with a regular expression.
  463. </p>
  464. <p>
  465. First, add <code>"regexp"</code> to the <code>import</code> list.
  466. Then we can create a global variable to store our validation
  467. expression:
  468. </p>
  469. {{code "doc/articles/wiki/final-noclosure.go" `/^var validPath/`}}
  470. <p>
  471. The function <code>regexp.MustCompile</code> will parse and compile the
  472. regular expression, and return a <code>regexp.Regexp</code>.
  473. <code>MustCompile</code> is distinct from <code>Compile</code> in that it will
  474. panic if the expression compilation fails, while <code>Compile</code> returns
  475. an <code>error</code> as a second parameter.
  476. </p>
  477. <p>
  478. Now, let's write a function that uses the <code>validPath</code>
  479. expression to validate path and extract the page title:
  480. </p>
  481. {{code "doc/articles/wiki/final-noclosure.go" `/func getTitle/` `/^}/`}}
  482. <p>
  483. If the title is valid, it will be returned along with a <code>nil</code>
  484. error value. If the title is invalid, the function will write a
  485. "404 Not Found" error to the HTTP connection, and return an error to the
  486. handler. To create a new error, we have to import the <code>errors</code>
  487. package.
  488. </p>
  489. <p>
  490. Let's put a call to <code>getTitle</code> in each of the handlers:
  491. </p>
  492. {{code "doc/articles/wiki/final-noclosure.go" `/^func viewHandler/` `/^}/`}}
  493. {{code "doc/articles/wiki/final-noclosure.go" `/^func editHandler/` `/^}/`}}
  494. {{code "doc/articles/wiki/final-noclosure.go" `/^func saveHandler/` `/^}/`}}
  495. <h2>Introducing Function Literals and Closures</h2>
  496. <p>
  497. Catching the error condition in each handler introduces a lot of repeated code.
  498. What if we could wrap each of the handlers in a function that does this
  499. validation and error checking? Go's
  500. <a href="/ref/spec#Function_literals">function
  501. literals</a> provide a powerful means of abstracting functionality
  502. that can help us here.
  503. </p>
  504. <p>
  505. First, we re-write the function definition of each of the handlers to accept
  506. a title string:
  507. </p>
  508. <pre>
  509. func viewHandler(w http.ResponseWriter, r *http.Request, title string)
  510. func editHandler(w http.ResponseWriter, r *http.Request, title string)
  511. func saveHandler(w http.ResponseWriter, r *http.Request, title string)
  512. </pre>
  513. <p>
  514. Now let's define a wrapper function that <i>takes a function of the above
  515. type</i>, and returns a function of type <code>http.HandlerFunc</code>
  516. (suitable to be passed to the function <code>http.HandleFunc</code>):
  517. </p>
  518. <pre>
  519. func makeHandler(fn func (http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
  520. return func(w http.ResponseWriter, r *http.Request) {
  521. // Here we will extract the page title from the Request,
  522. // and call the provided handler 'fn'
  523. }
  524. }
  525. </pre>
  526. <p>
  527. The returned function is called a closure because it encloses values defined
  528. outside of it. In this case, the variable <code>fn</code> (the single argument
  529. to <code>makeHandler</code>) is enclosed by the closure. The variable
  530. <code>fn</code> will be one of our save, edit, or view handlers.
  531. </p>
  532. <p>
  533. Now we can take the code from <code>getTitle</code> and use it here
  534. (with some minor modifications):
  535. </p>
  536. {{code "doc/articles/wiki/final.go" `/func makeHandler/` `/^}/`}}
  537. <p>
  538. The closure returned by <code>makeHandler</code> is a function that takes
  539. an <code>http.ResponseWriter</code> and <code>http.Request</code> (in other
  540. words, an <code>http.HandlerFunc</code>).
  541. The closure extracts the <code>title</code> from the request path, and
  542. validates it with the <code>TitleValidator</code> regexp. If the
  543. <code>title</code> is invalid, an error will be written to the
  544. <code>ResponseWriter</code> using the <code>http.NotFound</code> function.
  545. If the <code>title</code> is valid, the enclosed handler function
  546. <code>fn</code> will be called with the <code>ResponseWriter</code>,
  547. <code>Request</code>, and <code>title</code> as arguments.
  548. </p>
  549. <p>
  550. Now we can wrap the handler functions with <code>makeHandler</code> in
  551. <code>main</code>, before they are registered with the <code>http</code>
  552. package:
  553. </p>
  554. {{code "doc/articles/wiki/final.go" `/func main/` `/^}/`}}
  555. <p>
  556. Finally we remove the calls to <code>getTitle</code> from the handler functions,
  557. making them much simpler:
  558. </p>
  559. {{code "doc/articles/wiki/final.go" `/^func viewHandler/` `/^}/`}}
  560. {{code "doc/articles/wiki/final.go" `/^func editHandler/` `/^}/`}}
  561. {{code "doc/articles/wiki/final.go" `/^func saveHandler/` `/^}/`}}
  562. <h2>Try it out!</h2>
  563. <p>
  564. <a href="final.go">Click here to view the final code listing.</a>
  565. </p>
  566. <p>
  567. Recompile the code, and run the app:
  568. </p>
  569. <pre>
  570. $ go build wiki.go
  571. $ ./wiki
  572. </pre>
  573. <p>
  574. Visiting <a href="http://localhost:8080/view/ANewPage">http://localhost:8080/view/ANewPage</a>
  575. should present you with the page edit form. You should then be able to
  576. enter some text, click 'Save', and be redirected to the newly created page.
  577. </p>
  578. <h2>Other tasks</h2>
  579. <p>
  580. Here are some simple tasks you might want to tackle on your own:
  581. </p>
  582. <ul>
  583. <li>Store templates in <code>tmpl/</code> and page data in <code>data/</code>.
  584. <li>Add a handler to make the web root redirect to
  585. <code>/view/FrontPage</code>.</li>
  586. <li>Spruce up the page templates by making them valid HTML and adding some
  587. CSS rules.</li>
  588. <li>Implement inter-page linking by converting instances of
  589. <code>[PageName]</code> to <br>
  590. <code>&lt;a href="/view/PageName"&gt;PageName&lt;/a&gt;</code>.
  591. (hint: you could use <code>regexp.ReplaceAllFunc</code> to do this)
  592. </li>
  593. </ul>