notemplate.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. "fmt"
  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 viewHandler(w http.ResponseWriter, r *http.Request) {
  28. title := r.URL.Path[len("/view/"):]
  29. p, _ := loadPage(title)
  30. fmt.Fprintf(w, "<h1>%s</h1><div>%s</div>", p.Title, p.Body)
  31. }
  32. func editHandler(w http.ResponseWriter, r *http.Request) {
  33. title := r.URL.Path[len("/edit/"):]
  34. p, err := loadPage(title)
  35. if err != nil {
  36. p = &Page{Title: title}
  37. }
  38. fmt.Fprintf(w, "<h1>Editing %s</h1>"+
  39. "<form action=\"/save/%s\" method=\"POST\">"+
  40. "<textarea name=\"body\">%s</textarea><br>"+
  41. "<input type=\"submit\" value=\"Save\">"+
  42. "</form>",
  43. p.Title, p.Title, p.Body)
  44. }
  45. func main() {
  46. http.HandleFunc("/view/", viewHandler)
  47. http.HandleFunc("/edit/", editHandler)
  48. log.Fatal(http.ListenAndServe(":8080", nil))
  49. }