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