all repos

rss-tools @ aeb1a59

get rss feed from sources that(i need and) dont provide one

rss-tools/app/atom/feed.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
refactor atom feed builder, 14 days ago
1
package atom
2
3
import (
4
	"bytes"
5
	"encoding/xml"
6
	"io"
7
	"net/http"
8
	"strings"
9
	"time"
10
)
11
12
func NewFeed(title, id string) *Feed {
13
	return &Feed{
14
		Title:   title,
15
		ID:      id,
16
		Updated: Time(time.Now()),
17
		Author:  []*Person{{Name: "rss-tools"}},
18
	}
19
}
20
21
func (f *Feed) WithAuthor(name string) *Feed {
22
	name = strings.TrimSpace(name)
23
	if name == "" {
24
		return f
25
	}
26
	f.Author = []*Person{{Name: name}}
27
	return f
28
}
29
30
func (f *Feed) WithUpdated(updated time.Time) *Feed {
31
	if !updated.IsZero() {
32
		f.Updated = Time(updated)
33
	}
34
	return f
35
}
36
37
func (f *Feed) Add(entry *Entry) *Feed {
38
	if entry != nil {
39
		f.Entry = append(f.Entry, entry)
40
	}
41
	return f
42
}
43
44
func (f *Feed) WriteTo(w io.Writer) error {
45
	enc := xml.NewEncoder(w)
46
	enc.Indent("", "  ")
47
	return enc.Encode(f)
48
}
49
50
func (f *Feed) Bytes() ([]byte, error) {
51
	var buf bytes.Buffer
52
	if err := f.WriteTo(&buf); err != nil {
53
		return nil, err
54
	}
55
	return buf.Bytes(), nil
56
}
57
58
func (f *Feed) Render(w http.ResponseWriter) error {
59
	w.Header().Set("Content-Type", "application/atom+xml; charset=utf-8")
60
	return f.WriteTo(w)
61
}
62
63
func NewText(body, typ string) *Text {
64
	if body == "" && strings.TrimSpace(typ) == "" {
65
		return nil
66
	}
67
	if strings.TrimSpace(typ) == "" {
68
		typ = "text"
69
	}
70
	return &Text{Type: typ, Body: body}
71
}