forked from cshum/imagor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
52 lines (44 loc) · 984 Bytes
/
context.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
package imagor
import (
"context"
"errors"
"sync"
)
type imagorContextKey struct{}
type imagorContextRef struct {
funcs []func()
l sync.Mutex
}
func (r *imagorContextRef) Defer(fn func()) {
r.l.Lock()
r.funcs = append(r.funcs, fn)
r.l.Unlock()
}
func (r *imagorContextRef) Done() {
r.l.Lock()
for _, fn := range r.funcs {
fn()
}
r.funcs = nil
r.l.Unlock()
}
// WithContext context with imagor defer handling and cache
func WithContext(ctx context.Context) context.Context {
r := &imagorContextRef{}
ctx = context.WithValue(ctx, imagorContextKey{}, r)
go func() {
<-ctx.Done()
r.Done()
}()
return ctx
}
func mustContextValue(ctx context.Context) *imagorContextRef {
if r, ok := ctx.Value(imagorContextKey{}).(*imagorContextRef); ok && r != nil {
return r
}
panic(errors.New("not imagor context"))
}
// Defer add func to context, defer called at the end of request
func Defer(ctx context.Context, fn func()) {
mustContextValue(ctx).Defer(fn)
}