part2.go 873 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  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 main() {
  33. http.HandleFunc("/view/", viewHandler)
  34. log.Fatal(http.ListenAndServe(":8080", nil))
  35. }