-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhelpers.go
42 lines (38 loc) · 914 Bytes
/
helpers.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
package cache
import (
"time"
)
type timeOutResult[ResultType any] struct {
r ResultType
e error
}
func WithTimeout[ParamsType, ResultType any](f cacheGetterFunc[ParamsType, ResultType], t time.Duration, err error) cacheGetterFunc[ParamsType, ResultType] {
return func(v ParamsType) (ResultType, error) {
c := make(chan timeOutResult[ResultType])
go func() {
r, e := f(v)
c <- timeOutResult[ResultType]{r, e}
}()
select {
case r := <-c:
return r.r, r.e
case <-time.After(t):
}
var zero ResultType
return zero, err
}
}
func WithRetry[ParamsType, ResultType any](f cacheGetterFunc[ParamsType, ResultType], n int) cacheGetterFunc[ParamsType, ResultType] {
return func(v ParamsType) (ResultType, error) {
var lastError error
for i := 0; i < n; i++ {
r, e := f(v)
if e == nil {
return r, e
}
lastError = e
}
var zero ResultType
return zero, lastError
}
}