github.com/stingnevermore/go@v0.0.0-20180120041312-3810f5bfed72/doc/articles/wiki/notemplate.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  	"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 editHandler(w http.ResponseWriter, r *http.Request) {
    40  	title := r.URL.Path[len("/edit/"):]
    41  	p, err := loadPage(title)
    42  	if err != nil {
    43  		p = &Page{Title: title}
    44  	}
    45  	fmt.Fprintf(w, "<h1>Editing %s</h1>"+
    46  		"<form action=\"/save/%s\" method=\"POST\">"+
    47  		"<textarea name=\"body\">%s</textarea><br>"+
    48  		"<input type=\"submit\" value=\"Save\">"+
    49  		"</form>",
    50  		p.Title, p.Title, p.Body)
    51  }
    52  
    53  func main() {
    54  	http.HandleFunc("/view/", viewHandler)
    55  	http.HandleFunc("/edit/", editHandler)
    56  	log.Fatal(http.ListenAndServe(":8080", nil))
    57  }