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 5 package main 6 7 import ( 8 "fmt" 9 "io/ioutil" 10 "net/http" 11 ) 12 13 type Page struct { 14 Title string 15 Body []byte 16 } 17 18 func (p *Page) save() error { 19 filename := p.Title + ".txt" 20 return ioutil.WriteFile(filename, p.Body, 0600) 21 } 22 23 func loadPage(title string) (*Page, error) { 24 filename := title + ".txt" 25 body, err := ioutil.ReadFile(filename) 26 if err != nil { 27 return nil, err 28 } 29 return &Page{Title: title, Body: body}, nil 30 } 31 32 func viewHandler(w http.ResponseWriter, r *http.Request) { 33 title := r.URL.Path[len("/view/"):] 34 p, _ := loadPage(title) 35 fmt.Fprintf(w, "<h1>%s</h1><div>%s</div>", p.Title, p.Body) 36 } 37 38 func editHandler(w http.ResponseWriter, r *http.Request) { 39 title := r.URL.Path[len("/edit/"):] 40 p, err := loadPage(title) 41 if err != nil { 42 p = &Page{Title: title} 43 } 44 fmt.Fprintf(w, "<h1>Editing %s</h1>"+ 45 "<form action=\"/save/%s\" method=\"POST\">"+ 46 "<textarea name=\"body\">%s</textarea><br>"+ 47 "<input type=\"submit\" value=\"Save\">"+ 48 "</form>", 49 p.Title, p.Title, p.Body) 50 } 51 52 func main() { 53 http.HandleFunc("/view/", viewHandler) 54 http.HandleFunc("/edit/", editHandler) 55 http.ListenAndServe(":8080", nil) 56 } 57