Source file doc/articles/wiki/part2.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  	"fmt"
    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 viewHandler(w http.ResponseWriter, r *http.Request) {
    36  	title := r.URL.Path[len("/view/"):]
    37  	p, _ := loadPage(title)
    38  	fmt.Fprintf(w, "<h1>%s</h1><div>%s</div>", p.Title, p.Body)
    39  }
    40  
    41  func main() {
    42  	http.HandleFunc("/view/", viewHandler)
    43  	log.Fatal(http.ListenAndServe(":8080", nil))
    44  }
    45  

View as plain text