-
Notifications
You must be signed in to change notification settings - Fork 0
/
page.go
79 lines (70 loc) · 1.54 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package web
import (
"fmt"
"io"
"net/http"
"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(".")
}
// SaveTo saves the page to the given directory. Fails if
// page.Filename is empty.
func (p *Page) SaveTo(dir string) error {
if p.Filename == "" {
return fmt.Errorf("SaveTo: missing filename")
}
w, err := os.Create(path.Join(dir, p.Filename))
if err != nil {
return err
}
p.WriteTo(w)
w.Close()
return nil
}
// WriteTo writes the page using the given writer. Page.Filename
// extension decides format. .md for markdown, otherwise HTML.
// markdown, html otherwise.
func (p *Page) WriteTo(w io.Writer) (int64, error) {
switch path.Ext(p.Filename) {
case ".md":
enc := NewMarkdownEncoder(w)
if p.Element != nil {
enc.Encode(p.Element)
}
return enc.Written, *enc.err
default:
enc := NewHtmlEncoder(w)
if p.Element != nil {
enc.Encode(p.Element)
}
return enc.Written, *enc.err
}
}
func (p *Page) ServeHTTP(w http.ResponseWriter, r *http.Request) {
p.WriteTo(w)
}
type encoder interface {
Encode(t interface{}) error
}