-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathexample_test.go
70 lines (57 loc) · 1.34 KB
/
example_test.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 future_test
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"github.com/sentientmonkey/future"
)
func ExampleFuture() {
f := future.NewFuture(func() (future.Value, error) {
return http.Get("http://golang.org/")
})
result, err := f.Get()
if err != nil {
fmt.Printf("Got error: %s\n", err)
return
}
response := result.(*http.Response)
defer response.Body.Close()
fmt.Printf("Got result: %d\n", response.StatusCode)
// Output: Got result: 200
}
func ExamplePromise() {
p := future.NewPromise(func() (future.Value, error) {
return http.Get("http://golang.org/")
})
p = p.Then(func(value future.Value) (future.Value, error) {
response := value.(*http.Response)
defer response.Body.Close()
b, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
return string(b), nil
})
p = p.Then(func(value future.Value) (future.Value, error) {
body := value.(string)
r, err := regexp.Compile("<title>(.*)</title>")
if err != nil {
return nil, err
}
match := r.FindStringSubmatch(body)
if len(match) < 1 {
return nil, errors.New("Title not found")
}
return match[1], nil
})
result, err := p.Get()
if err != nil {
fmt.Printf("Got error: %s\n", err)
return
}
s := result.(string)
fmt.Printf("Got result: %s\n", s)
// Output: Got result: The Go Programming Language
}