Source file doc/articles/wiki/part1.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  	"os"
    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 os.WriteFile(filename, p.Body, 0600)
    22  }
    23  
    24  func loadPage(title string) (*Page, error) {
    25  	filename := title + ".txt"
    26  	body, err := os.ReadFile(filename)
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  	return &Page{Title: title, Body: body}, nil
    31  }
    32  
    33  func main() {
    34  	p1 := &Page{Title: "TestPage", Body: []byte("This is a sample Page.")}
    35  	p1.save()
    36  	p2, _ := loadPage("TestPage")
    37  	fmt.Println(string(p2.Body))
    38  }
    39  

View as plain text