final-parsetemplate.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
  54. t, err := template.ParseFiles(tmpl + ".html")
  55. if err != nil {
  56. http.Error(w, err.Error(), http.StatusInternalServerError)
  57. return
  58. }
  59. err = t.Execute(w, p)
  60. if err != nil {
  61. http.Error(w, err.Error(), http.StatusInternalServerError)
  62. }
  63. }
  64. var validPath = regexp.MustCompile("^/(edit|save|view)/([a-zA-Z0-9]+)$")
  65. func makeHandler(fn func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc {
  66. return func(w http.ResponseWriter, r *http.Request) {
  67. m := validPath.FindStringSubmatch(r.URL.Path)
  68. if m == nil {
  69. http.NotFound(w, r)
  70. return
  71. }
  72. fn(w, r, m[2])
  73. }
  74. }
  75. func main() {
  76. http.HandleFunc("/view/", makeHandler(viewHandler))
  77. http.HandleFunc("/edit/", makeHandler(editHandler))
  78. http.HandleFunc("/save/", makeHandler(saveHandler))
  79. log.Fatal(http.ListenAndServe(":8080", nil))
  80. }