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