-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch.go
More file actions
88 lines (76 loc) · 1.53 KB
/
Copy pathfetch.go
File metadata and controls
88 lines (76 loc) · 1.53 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package eutil
import (
"bytes"
"net/http"
"sync"
"time"
"github.com/pkg/errors"
)
type (
catchFunc = func(res *http.Response, err error)
thenFunc = func(*http.Response)
promise struct {
res *http.Response
execFn func()
err error
pending bool
thenFns []thenFunc
catchFns []catchFunc
wg *sync.WaitGroup
}
)
func Fetch(method, url string, body []byte, headers map[string]string, timeout time.Duration) *promise {
if timeout == 0 {
timeout = 3 * time.Second
}
pro := &promise{
pending: true,
wg: &sync.WaitGroup{},
}
pro.execFn = func() {
defer pro.wg.Done()
pro.pending = false
req, err := http.NewRequest(method, url, bytes.NewReader(body))
if err != nil {
pro.err = err
return
}
for k, v := range headers {
req.Header.Add(k, v)
}
client := &http.Client{Timeout: timeout}
res, err := client.Do(req)
if err != nil {
pro.err = err
} else if res.StatusCode != http.StatusOK {
pro.err = errors.Errorf("status code is not ok: [%v]", res.Status)
}
pro.res = res
}
return pro
}
func (p *promise) Then(fn thenFunc) *promise {
p.thenFns = append(p.thenFns, fn)
return p
}
func (p *promise) Catch(fn catchFunc) *promise {
p.catchFns = append(p.catchFns, fn)
return p
}
func (p *promise) Await() (success bool) {
p.wg.Add(1)
go p.execFn()
p.wg.Wait()
if p.err != nil {
success = false
for _, catchFn := range p.catchFns {
catchFn(p.res, p.err)
}
} else {
success = true
for _, thenFn := range p.thenFns {
thenFn(p.res)
}
}
return
}