~chrisppy/go-barefeed

go-barefeed/barefeed.go -rw-r--r-- 1.2 KiB
f9d9820fChris Palmer fix doc link in readme 8 months ago
                                                                                
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
// Package barefeed is an implementation of the barefeed message format for Go.
//
// https://git.sr.ht/~chrisppy/go-barefeed
package barefeed

import (
	"fmt"
	"io"

	"git.sr.ht/~sircmpwn/go-bare"
)

// FeedMap map of Linked
type FeedMap map[string]Linked

// Linked containing the linkage between a Feed and Entry
type Linked struct {
	Feed    Feed
	Entries map[string]Entry
}

// Read will open the provided reader and load it into the FeedEntry
func (d FeedMap) Read(reader io.Reader) (err error) {
	var b Bin
	if err = bare.UnmarshalReader(reader, &b); err != nil {
		return
	}

	switch content := b.Content.(type) {
	case *Feed:
		l := Linked{
			Feed:    *content,
			Entries: make(map[string]Entry),
		}
		if v, ok := d[content.FeedID]; ok {
			l.Entries = v.Entries
		}

		d[content.FeedID] = l
	case *Entry:
		if _, ok := d[content.FeedID]; ok {
			d[content.FeedID].Entries[content.EntryID] = *content
			return
		}

		d[content.FeedID] = Linked{
			Entries: map[string]Entry{
				content.EntryID: *content,
			},
		}
	default:
		err = fmt.Errorf("unknown type provided %+v", content)
	}

	return
}

// Write will output the Bin to the provided io writer
func (d Bin) Write(writer io.Writer) error {
	w := bare.NewWriter(writer)
	return bare.MarshalWriter(w, &d)
}