github.com/varialus/godfly@v0.0.0-20130904042352-1934f9f095ab/doc/articles/wiki/part3-errorhandling.go (about)

     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  	"html/template"
     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  const lenPath = len("/view/")
    33  
    34  func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
    35  	t, _ := template.ParseFiles(tmpl + ".html")
    36  	t.Execute(w, p)
    37  }
    38  
    39  func viewHandler(w http.ResponseWriter, r *http.Request) {
    40  	title := r.URL.Path[lenPath:]
    41  	p, err := loadPage(title)
    42  	if err != nil {
    43  		http.Redirect(w, r, "/edit/"+title, http.StatusFound)
    44  		return
    45  	}
    46  	renderTemplate(w, "view", p)
    47  }
    48  
    49  func editHandler(w http.ResponseWriter, r *http.Request) {
    50  	title := r.URL.Path[lenPath:]
    51  	p, err := loadPage(title)
    52  	if err != nil {
    53  		p = &Page{Title: title}
    54  	}
    55  	renderTemplate(w, "edit", p)
    56  }
    57  
    58  func saveHandler(w http.ResponseWriter, r *http.Request) {
    59  	title := r.URL.Path[lenPath:]
    60  	body := r.FormValue("body")
    61  	p := &Page{Title: title, Body: []byte(body)}
    62  	err := p.save()
    63  	if err != nil {
    64  		http.Error(w, err.Error(), http.StatusInternalServerError)
    65  		return
    66  	}
    67  	http.Redirect(w, r, "/view/"+title, http.StatusFound)
    68  }
    69  
    70  func main() {
    71  	http.HandleFunc("/view/", viewHandler)
    72  	http.HandleFunc("/edit/", editHandler)
    73  	http.HandleFunc("/save/", saveHandler)
    74  	http.ListenAndServe(":8080", nil)
    75  }