final.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. package main
  5. import (
  6. "html/template"
  7. "io/ioutil"
  8. "log"
  9. "net/http"
  10. "regexp"
  11. )
  12. type Page struct {
  13. Title string
  14. Body []byte
  15. }
  16. func (p *Page) save() error {
  17. filename := p.Title + ".txt"
  18. return ioutil.WriteFile(filename, p.Body, 0600)
  19. }
  20. func loadPage(title string) (*Page, error) {
  21. filename := title + ".txt"
  22. body, err := ioutil.ReadFile(filename)
  23. if err != nil {
  24. return nil, err
  25. }
  26. return &Page{Title: title, Body: body}, nil
  27. }
  28. func viewHandler(w http.ResponseWriter, r *http.Request, title string) {
  29. p, err := loadPage(title)
  30. if err != nil {
  31. http.Redirect(w, r, "/edit/"+title, http.StatusFound)
  32. return
  33. }
  34. renderTemplate(w, "view", p)
  35. }
  36. func editHandler(w http.ResponseWriter, r *http.Request, title string) {
  37. p, err := loadPage(title)
  38. if err != nil {
  39. p = &Page{Title: title}
  40. }
  41. renderTemplate(w, "edit", p)
  42. }
  43. func saveHandler(w http.ResponseWriter, r *http.Request, title string) {
  44. body := r.FormValue("body")
  45. p := &Page{Title: title, Body: []byte(body)}
  46. err := p.save()
  47. if err != nil {
  48. http.Error(w, err.Error(), http.StatusInternalServerError)
  49. return
  50. }
  51. http.Redirect(w, r, "/view/"+title, http.StatusFound)
  52. }
  53. var templates = template.Must(template.ParseFiles("edit.html", "view.html"))
  54. func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
  55. err := templates.ExecuteTemplate(w, tmpl+".html", p)
  56. if err != nil {
  57. http.Error(w, err.Error(), http.StatusInternalServerError)
  58. }
  59. }
  60. var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$")
  61. func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
  62. return func(w http.ResponseWriter, r *http.Request) {
  63. m := validPath.FindStringSubmatch(r.URL.Path)
  64. if m == nil {
  65. http.NotFound(w, r)
  66. return
  67. }
  68. fn(w, r, m[2])
  69. }
  70. }
  71. func main() {
  72. http.HandleFunc("/view/", makeHandler(viewHandler))
  73. http.HandleFunc("/edit/", makeHandler(editHandler))
  74. http.HandleFunc("/save/", makeHandler(saveHandler))
  75. log.Fatal(http.ListenAndServe(":8080", nil))
  76. }