wiki_part2.go 712 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. )
  7. type Page struct {
  8. Title string
  9. Body []byte
  10. }
  11. func (p *Page) save() error {
  12. filename := p.Title + ".txt"
  13. return ioutil.WriteFile(filename, p.Body, 0600)
  14. }
  15. func load(title string) (*Page, error) {
  16. filename := title + ".txt"
  17. body, err := ioutil.ReadFile(filename)
  18. if err != nil {
  19. return nil, err
  20. }
  21. return &Page{Title: title, Body: body}, nil
  22. }
  23. const lenPath = len("/view/")
  24. func viewHandler(w http.ResponseWriter, r *http.Request) {
  25. title := r.URL.Path[lenPath:]
  26. p, _ := load(title)
  27. fmt.Fprintf(w, "<h1>%s</h1><div>%s</div>", p.Title, p.Body)
  28. }
  29. func main() {
  30. http.HandleFunc("/view/", viewHandler)
  31. http.ListenAndServe(":8080", nil)
  32. }