Source file doc/articles/wiki/part3.go

     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  //go:build ignore
     6  
     7  package main
     8  
     9  import (
    10  	"html/template"
    11  	"log"
    12  	"net/http"
    13  	"os"
    14  )
    15  
    16  type Page struct {
    17  	Title string
    18  	Body  []byte
    19  }
    20  
    21  func (p *Page) save() error {
    22  	filename := p.Title + ".txt"
    23  	return os.WriteFile(filename, p.Body, 0600)
    24  }
    25  
    26  func loadPage(title string) (*Page, error) {
    27  	filename := title + ".txt"
    28  	body, err := os.ReadFile(filename)
    29  	if err != nil {
    30  		return nil, err
    31  	}
    32  	return &Page{Title: title, Body: body}, nil
    33  }
    34  
    35  func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
    36  	t, _ := template.ParseFiles(tmpl + ".html")
    37  	t.Execute(w, p)
    38  }
    39  
    40  func viewHandler(w http.ResponseWriter, r *http.Request) {
    41  	title := r.URL.Path[len("/view/"):]
    42  	p, _ := loadPage(title)
    43  	renderTemplate(w, "view", p)
    44  }
    45  
    46  func editHandler(w http.ResponseWriter, r *http.Request) {
    47  	title := r.URL.Path[len("/edit/"):]
    48  	p, err := loadPage(title)
    49  	if err != nil {
    50  		p = &Page{Title: title}
    51  	}
    52  	renderTemplate(w, "edit", p)
    53  }
    54  
    55  func main() {
    56  	http.HandleFunc("/view/", viewHandler)
    57  	http.HandleFunc("/edit/", editHandler)
    58  	//http.HandleFunc("/save/", saveHandler)
    59  	log.Fatal(http.ListenAndServe(":8080", nil))
    60  }
    61  

View as plain text