-
Notifications
You must be signed in to change notification settings - Fork 0
/
page.go
57 lines (50 loc) · 1.02 KB
/
page.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package web
import (
"fmt"
"io"
"os"
"path"
)
// NewPage returns a page ready to be rendered. Filename is empty and
// must be set before saving.
func NewPage(el *Element) *Page {
return &Page{
Element: el,
}
}
// NewFile returns a page with filename set, ready to be saved.
func NewFile(filename string, el *Element) *Page {
return &Page{
Filename: filename,
Element: el,
}
}
type Page struct {
Filename string
*Element
}
// SaveAs sets filename and then save to the current directory.
func (me *Page) SaveAs(filename string) error {
me.Filename = filename
return me.SaveTo(".")
}
func (p *Page) SaveTo(dir string) error {
if p.Filename == "" {
return fmt.Errorf("page SaveTo: missing filename")
}
w, err := os.Create(path.Join(dir, p.Filename))
if err != nil {
return err
}
p.WriteTo(w)
w.Close()
return nil
}
func (p *Page) WriteTo(w io.Writer) (int64, error) {
hw := NewHtmlWriter(w)
hw.Print("<!DOCTYPE html>\n\n")
if p.Element != nil {
hw.WriteHtml(p.Element)
}
return hw.Written, *hw.err
}