github.com/varialus/godfly@v0.0.0-20130904042352-1934f9f095ab/doc/articles/wiki/index.html (about)

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