final-noerror.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. t, _ := template.ParseFiles("edit.html")
  34. t.Execute(w, p)
  35. }
  36. func viewHandler(w http.ResponseWriter, r *http.Request) {
  37. title := r.URL.Path[len("/view/"):]
  38. p, _ := loadPage(title)
  39. t, _ := template.ParseFiles("view.html")
  40. t.Execute(w, p)
  41. }
  42. func main() {
  43. http.HandleFunc("/view/", viewHandler)
  44. http.HandleFunc("/edit/", editHandler)
  45. log.Fatal(http.ListenAndServe(":8080", nil))
  46. }