File tree 1 file changed +41
-0
lines changed
1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ package redis
2
+
3
+ import (
4
+ "sync"
5
+ "time"
6
+ )
7
+
8
+ type TokenManager struct {
9
+ token string
10
+ expiresAt time.Time
11
+ mutex sync.Mutex
12
+ }
13
+
14
+ func NewTokenManager () * TokenManager {
15
+ return & TokenManager {}
16
+ }
17
+
18
+ func (tm * TokenManager ) SetToken (token string , ttl time.Duration ) {
19
+ tm .mutex .Lock ()
20
+ defer tm .mutex .Unlock ()
21
+ tm .token = token
22
+ tm .expiresAt = time .Now ().Add (ttl )
23
+ }
24
+
25
+ func (tm * TokenManager ) GetToken () (string , bool ) {
26
+ tm .mutex .Lock ()
27
+ defer tm .mutex .Unlock ()
28
+ if time .Now ().After (tm .expiresAt ) {
29
+ return "" , false
30
+ }
31
+ return tm .token , true
32
+ }
33
+
34
+ func (tm * TokenManager ) RefreshToken (fetchToken func () (string , time.Duration , error )) error {
35
+ token , ttl , err := fetchToken ()
36
+ if err != nil {
37
+ return err
38
+ }
39
+ tm .SetToken (token , ttl )
40
+ return nil
41
+ }
You can’t perform that action at this time.
0 commit comments