mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
update the news fetcher example
This commit is contained in:
52
examples/news_fetcher.v
Normal file
52
examples/news_fetcher.v
Normal file
@ -0,0 +1,52 @@
|
||||
import http
|
||||
import json
|
||||
import sync
|
||||
import time
|
||||
|
||||
const (
|
||||
NR_THREADS = 8
|
||||
)
|
||||
|
||||
struct Story {
|
||||
title string
|
||||
}
|
||||
|
||||
struct Fetcher {
|
||||
mut:
|
||||
mu sync.Mutex
|
||||
ids []int
|
||||
cursor int
|
||||
}
|
||||
|
||||
fn (f mut Fetcher) fetch() {
|
||||
for {
|
||||
f.mu.lock()
|
||||
if f.cursor >= f.ids.len {
|
||||
return
|
||||
}
|
||||
id := f.ids[f.cursor]
|
||||
f.cursor++
|
||||
f.mu.unlock()
|
||||
resp := http.get('https://hacker-news.firebaseio.com/v0/item/${id}.json')
|
||||
story := json.decode(Story, resp) or {
|
||||
exit('failed to decode a story')
|
||||
}
|
||||
println('#$f.cursor) $story.title')
|
||||
}
|
||||
}
|
||||
|
||||
// Fetches top HN stories in 8 coroutines
|
||||
fn main() {
|
||||
resp := http.get('https://hacker-news.firebaseio.com/v0/topstories.json')
|
||||
ids := json.decode( []int, resp) or {
|
||||
println('failed to fetch topstories.json')
|
||||
return
|
||||
}
|
||||
fetcher := &Fetcher{ids: ids}
|
||||
for i := 0; i < NR_THREADS; i++ {
|
||||
go fetcher.fetch()
|
||||
}
|
||||
println(fetcher.ids)
|
||||
time.sleep(5)
|
||||
}
|
||||
|
Reference in New Issue
Block a user