File tree Expand file tree Collapse file tree 4 files changed +29
-10
lines changed
Expand file tree Collapse file tree 4 files changed +29
-10
lines changed Original file line number Diff line number Diff line change 11package featureflag
22
33import (
4- "sync"
5-
64 "github.com/sirupsen/logrus"
5+ "go.uber.org/atomic"
6+ "unsafe"
77)
88
9- var globalLock sync.Mutex
10- var globalClient Client = MockClient {}
9+ // See https://blog.dubbelboer.com/2015/08/23/rwmutex-vs-atomicvalue-vs-unsafepointer.html
10+ var (
11+ defaultClient Client = MockClient {}
12+ globalClient = atomic .NewUnsafePointer (unsafe .Pointer (& defaultClient ))
13+ )
1114
1215func SetGlobalClient (client Client ) {
1316 if client == nil {
1417 return
1518 }
16- globalLock .Lock ()
17- globalClient = client
18- globalLock .Unlock ()
19+ globalClient .Store (unsafe .Pointer (& client ))
1920}
2021
2122func GetGlobalClient () Client {
22- globalLock .Lock ()
23- defer globalLock .Unlock ()
24- return globalClient
23+ c := (* Client )(globalClient .Load ())
24+ return * c
2525}
2626
2727// Init will initialize global client with a launch darkly client
Original file line number Diff line number Diff line change 1+ package featureflag
2+
3+ import (
4+ "github.com/stretchr/testify/require"
5+ "testing"
6+ )
7+
8+ func TestGlobalAccess (t * testing.T ) {
9+ // initial value should be default
10+ require .Equal (t , defaultClient , GetGlobalClient ())
11+
12+ // setting new global should be reflected
13+ n := & ldClient {}
14+ SetGlobalClient (n )
15+ require .Equal (t , n , GetGlobalClient ())
16+ }
Original file line number Diff line number Diff line change @@ -36,6 +36,7 @@ require (
3636 github.com/tidwall/pretty v1.0.1 // indirect
3737 github.com/xtgo/uuid v0.0.0-20140804021211-a0b114877d4c // indirect
3838 go.mongodb.org/mongo-driver v1.9.0
39+ go.uber.org/atomic v1.9.0
3940 golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc
4041 gopkg.in/DataDog/dd-trace-go.v1 v1.34.0
4142 gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect
Original file line number Diff line number Diff line change @@ -389,6 +389,8 @@ go.mongodb.org/mongo-driver v1.9.0/go.mod h1:0sQWfOeY63QTntERDJJ/0SuKK0T1uVSgKCu
389389go.opencensus.io v0.21.0 /go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU =
390390go.opencensus.io v0.22.0 /go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8 =
391391go.uber.org/atomic v1.4.0 /go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE =
392+ go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE =
393+ go.uber.org/atomic v1.9.0 /go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc =
392394go.uber.org/multierr v1.1.0 /go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0 =
393395go.uber.org/zap v1.10.0 /go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q =
394396golang.org/x/crypto v0.0.0-20180904163835-0709b304e793 /go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4 =
You can’t perform that action at this time.
0 commit comments