File tree 2 files changed +27
-1
lines changed
2 files changed +27
-1
lines changed Original file line number Diff line number Diff line change 4
4
5
5
package user
6
6
7
+ import "sync"
8
+
7
9
// Current returns the current user.
8
10
func Current () (* User , error ) {
9
- return current ()
11
+ cache .Do (func () { cache .u , cache .err = current () })
12
+ if cache .err != nil {
13
+ return nil , cache .err
14
+ }
15
+ u := * cache .u // copy
16
+ return & u , nil
17
+ }
18
+
19
+ // cache of the current user
20
+ var cache struct {
21
+ sync.Once
22
+ u * User
23
+ err error
10
24
}
11
25
12
26
// Lookup looks up a user by username. If the user cannot be found, the
13
27
// returned error is of type UnknownUserError.
14
28
func Lookup (username string ) (* User , error ) {
29
+ if u , err := Current (); err == nil && u .Username == username {
30
+ return u , err
31
+ }
15
32
return lookupUser (username )
16
33
}
17
34
18
35
// LookupId looks up a user by userid. If the user cannot be found, the
19
36
// returned error is of type UnknownUserIdError.
20
37
func LookupId (uid string ) (* User , error ) {
38
+ if u , err := Current (); err == nil && u .Uid == uid {
39
+ return u , err
40
+ }
21
41
return lookupUserId (uid )
22
42
}
23
43
Original file line number Diff line number Diff line change @@ -31,6 +31,12 @@ func TestCurrent(t *testing.T) {
31
31
}
32
32
}
33
33
34
+ func BenchmarkCurrent (b * testing.B ) {
35
+ for i := 0 ; i < b .N ; i ++ {
36
+ Current ()
37
+ }
38
+ }
39
+
34
40
func compare (t * testing.T , want , got * User ) {
35
41
if want .Uid != got .Uid {
36
42
t .Errorf ("got Uid=%q; want %q" , got .Uid , want .Uid )
You can’t perform that action at this time.
0 commit comments