final-template.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. )
  11. type Page struct {
  12. Title string
  13. Body []byte
  14. }
  15. func (p *Page) save() error {
  16. filename := p.Title + ".txt"
  17. return ioutil.WriteFile(filename, p.Body, 0600)
  18. }
  19. func loadPage(title string) (*Page, error) {
  20. filename := title + ".txt"
  21. body, err := ioutil.ReadFile(filename)
  22. if err != nil {
  23. return nil, err
  24. }
  25. return &Page{Title: title, Body: body}, nil
  26. }
  27. func editHandler(w http.ResponseWriter, r *http.Request) {
  28. title := r.URL.Path[len("/edit/"):]
  29. p, err := loadPage(title)
  30. if err != nil {
  31. p = &Page{Title: title}
  32. }
  33. renderTemplate(w, "edit", p)
  34. }
  35. func viewHandler(w http.ResponseWriter, r *http.Request) {
  36. title := r.URL.Path[len("/view/"):]
  37. p, _ := loadPage(title)
  38. renderTemplate(w, "view", p)
  39. }
  40. func saveHandler(w http.ResponseWriter, r *http.Request) {
  41. title := r.URL.Path[len("/save/"):]
  42. body := r.FormValue("body")
  43. p := &Page{Title: title, Body: []byte(body)}
  44. p.save()
  45. http.Redirect(w, r, "/view/"+title, http.StatusFound)
  46. }
  47. func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
  48. t, _ := template.ParseFiles(tmpl + ".html")
  49. t.Execute(w, p)
  50. }
  51. func main() {
  52. http.HandleFunc("/view/", viewHandler)
  53. http.HandleFunc("/edit/", editHandler)
  54. http.HandleFunc("/save/", saveHandler)
  55. log.Fatal(http.ListenAndServe(":8080", nil))
  56. }