-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.go
70 lines (61 loc) · 1.82 KB
/
main.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
package main
//go:generate go run ../../cmd/gorx/main.go -o rx/rx.go --import=net/http rx *http.Response string
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/alecthomas/gorx/examples/complex/rx"
)
func GetCached(url string) *rx.ResponseStream {
fmt.Printf("No cache entry for %s\n", url)
return rx.ThrowResponse(errors.New("not implemented"))
}
func SetCached(response *http.Response) {
fmt.Printf("Caching %s\n", response.Request.URL)
}
func Get(url string) *rx.ResponseStream {
return rx.CreateResponse(func(observer rx.ResponseObserver, subscription rx.Subscription) {
response, err := http.Get(url)
if err != nil {
observer.Error(err)
}
if response.StatusCode < 200 || response.StatusCode > 299 {
observer.Error(errors.New(http.StatusText(response.StatusCode)))
return
}
observer.Next(response)
observer.Complete()
})
}
func URLForArticle(article string) string {
return "http://en.wikipedia.org/wiki/" + article
}
func LogError(err error) {
fmt.Printf("error: %s\n", err)
}
func GetWikipediaArticles(timeout time.Duration, articles ...string) *rx.ResponseStream {
// Try cached URL first, then recover with remote URL and
// finally recover with an empty stream.
return rx.FromStringArray(articles).
Map(URLForArticle).
FlatMapResponse(func(url string) rx.ResponseObservable {
remote := Get(url).
Timeout(timeout).
Do(SetCached).
DoOnError(LogError).
Catch(rx.EmptyResponse())
return GetCached(url).
Catch(remote)
})
}
func main() {
GetWikipediaArticles(time.Second*5, "MinHash", "Streaming_algorithm", "A MISSING PAGE", "ANOTHER MISSING PAGE").
Do(func(response *http.Response) {
defer response.Body.Close()
content, _ := ioutil.ReadAll(response.Body)
fmt.Printf("Retrieved %d bytes from %s\n", len(content), response.Request.URL)
}).
Wait()
}