use a real context w/ deadline

master
magical 2021-12-31 09:03:45 +00:00
parent c305e96334
commit 808cc164f1
1 changed files with 16 additions and 6 deletions

22
main.go
View File

@ -23,12 +23,15 @@ func main() {
NewFeed("https://tilde.town/~magical/404.xml"), NewFeed("https://tilde.town/~magical/404.xml"),
} }
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
var wg sync.WaitGroup var wg sync.WaitGroup
wg.Add(len(sources)) wg.Add(len(sources))
for i := range sources { for i := range sources {
src := sources[i] src := sources[i]
go func() { go func() {
src.update() src.update(ctx)
wg.Done() wg.Done()
}() }()
} }
@ -36,12 +39,21 @@ func main() {
for _, src := range sources { for _, src := range sources {
fmt.Println(src.Title, src.Error, src.LastStatus) fmt.Println(src.Title, src.Error, src.LastStatus)
for i, x := range src.Items {
if i > 5 {
break
}
fmt.Println("\t", x.PublishedParsed.Format(time.Stamp), x.Title)
}
} }
src := NewMastoSource("https://tilde.town/~magical/masto_test.html") src := NewMastoSource("https://tilde.town/~magical/masto_test.html")
src.update(context.Background()) src.update(ctx)
fmt.Println(src.Title, src.Error, src.LastStatus) fmt.Println(src.Title, src.Error, src.LastStatus)
for _, x := range src.Items { for i, x := range src.Items {
if i > 5 {
break
}
d, _ := time.Parse(time.RFC3339, x.PublishedString) d, _ := time.Parse(time.RFC3339, x.PublishedString)
fmt.Println("\t", d.Format(time.Stamp), x.Content) fmt.Println("\t", d.Format(time.Stamp), x.Content)
} }
@ -84,13 +96,11 @@ func NewFeed(url string) *FeedSource {
} }
} }
func (src *FeedSource) update() { func (src *FeedSource) update(ctx context.Context) {
src.mu.Lock() src.mu.Lock()
defer src.mu.Unlock() defer src.mu.Unlock()
fp := gofeed.NewParser() fp := gofeed.NewParser()
ctx := context.TODO()
req, err := http.NewRequest("GET", src.URL, nil) req, err := http.NewRequest("GET", src.URL, nil)
if err != nil { if err != nil {
src.Error = fmt.Errorf("error fetching %q: %w", src.URL, err) src.Error = fmt.Errorf("error fetching %q: %w", src.URL, err)