part3.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
  28. t, _ := template.ParseFiles(tmpl + ".html")
  29. t.Execute(w, p)
  30. }
  31. func viewHandler(w http.ResponseWriter, r *http.Request) {
  32. title := r.URL.Path[len("/view/"):]
  33. p, _ := loadPage(title)
  34. renderTemplate(w, "view", p)
  35. }
  36. func editHandler(w http.ResponseWriter, r *http.Request) {
  37. title := r.URL.Path[len("/edit/"):]
  38. p, err := loadPage(title)
  39. if err != nil {
  40. p = &Page{Title: title}
  41. }
  42. renderTemplate(w, "edit", p)
  43. }
  44. func main() {
  45. http.HandleFunc("/view/", viewHandler)
  46. http.HandleFunc("/edit/", editHandler)
  47. //http.HandleFunc("/save/", saveHandler)
  48. log.Fatal(http.ListenAndServe(":8080", nil))
  49. }