part1.go 727 B

123456789101112131415161718192021222324252627282930313233343536
  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. package main
  5. import (
  6. "fmt"
  7. "io/ioutil"
  8. )
  9. type Page struct {
  10. Title string
  11. Body []byte
  12. }
  13. func (p *Page) save() error {
  14. filename := p.Title + ".txt"
  15. return ioutil.WriteFile(filename, p.Body, 0600)
  16. }
  17. func loadPage(title string) (*Page, error) {
  18. filename := title + ".txt"
  19. body, err := ioutil.ReadFile(filename)
  20. if err != nil {
  21. return nil, err
  22. }
  23. return &Page{Title: title, Body: body}, nil
  24. }
  25. func main() {
  26. p1 := &Page{Title: "TestPage", Body: []byte("This is a sample Page.")}
  27. p1.save()
  28. p2, _ := loadPage("TestPage")
  29. fmt.Println(string(p2.Body))
  30. }