-
Notifications
You must be signed in to change notification settings - Fork 2
/
timeout.go
41 lines (35 loc) · 838 Bytes
/
timeout.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
package mongoproxy
import (
"errors"
"time"
)
var errTimeout error
func init() {
errTimeout = errors.New("operation timed out")
}
type response struct {
value interface{}
err error
}
// Runs the block and waits at most timeout for the block to finish. If
// the block does not finish in time, returns a timeout error, which can
// be checked by IsTimeout(err).
func TimeoutIn(block func() (interface{}, error), timeout time.Duration) (
interface{}, error) {
ch := make(chan *response, 1)
go func() {
value, err := block()
ch <- &response{value: value, err: err}
}()
timer := time.After(timeout)
select {
case value := <-ch:
return value.value, value.err
case <-timer:
return nil, errTimeout
}
}
// Returns whether or not this error is a timeout.
func IsTimeout(err error) bool {
return err == errTimeout
}