doc/articles/wiki/final.go - ActiveState ActiveGo 1.8
...

Source file doc/articles/wiki/final.go

     1	// Copyright 2010 The Go Authors. All rights reserved.
     2	// Use of this source code is governed by a BSD-style
     3	// license that can be found in the LICENSE file.
     4	
     5	package main
     6	
     7	import (
     8		"html/template"
     9		"io/ioutil"
    10		"net/http"
    11		"regexp"
    12	)
    13	
    14	type Page struct {
    15		Title string
    16		Body  []byte
    17	}
    18	
    19	func (p *Page) save() error {
    20		filename := p.Title + ".txt"
    21		return ioutil.WriteFile(filename, p.Body, 0600)
    22	}
    23	
    24	func loadPage(title string) (*Page, error) {
    25		filename := title + ".txt"
    26		body, err := ioutil.ReadFile(filename)
    27		if err != nil {
    28			return nil, err
    29		}
    30		return &Page{Title: title, Body: body}, nil
    31	}
    32	
    33	func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
    34		p, err := loadPage(title)
    35		if err != nil {
    36			http.Redirect(w, r, "/edit/"+title, http.StatusFound)
    37			return
    38		}
    39		renderTemplate(w, "view", p)
    40	}
    41	
    42	func editHandler(w http.ResponseWriter, r *http.Request, title string) {
    43		p, err := loadPage(title)
    44		if err != nil {
    45			p = &Page{Title: title}
    46		}
    47		renderTemplate(w, "edit", p)
    48	}
    49	
    50	func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
    51		body := r.FormValue("body")
    52		p := &Page{Title: title, Body: []byte(body)}
    53		err := p.save()
    54		if err != nil {
    55			http.Error(w, err.Error(), http.StatusInternalServerError)
    56			return
    57		}
    58		http.Redirect(w, r, "/view/"+title, http.StatusFound)
    59	}
    60	
    61	var templates = template.Must(template.ParseFiles("edit.html", "view.html"))
    62	
    63	func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
    64		err := templates.ExecuteTemplate(w, tmpl+".html", p)
    65		if err != nil {
    66			http.Error(w, err.Error(), http.StatusInternalServerError)
    67		}
    68	}
    69	
    70	var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$")
    71	
    72	func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
    73		return func(w http.ResponseWriter, r *http.Request) {
    74			m := validPath.FindStringSubmatch(r.URL.Path)
    75			if m == nil {
    76				http.NotFound(w, r)
    77				return
    78			}
    79			fn(w, r, m[2])
    80		}
    81	}
    82	
    83	func main() {
    84		http.HandleFunc("/view/", makeHandler(viewHandler))
    85		http.HandleFunc("/edit/", makeHandler(editHandler))
    86		http.HandleFunc("/save/", makeHandler(saveHandler))
    87	
    88		http.ListenAndServe(":8080", nil)
    89	}
    90	

View as plain text