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