99 "net"
1010 "net/http"
1111 "strings"
12+ "sync"
1213 "time"
1314
1415 "github.com/fatih/color"
@@ -21,7 +22,8 @@ type ResponseInfo struct {
2122}
2223
2324var (
24- timeout = 5 * time .Second
25+ timeout = 5 * time .Second
26+ fastIPCacheMu sync.RWMutex
2527)
2628var FastIpCache = ""
2729
@@ -53,6 +55,25 @@ func GetFastIP(domain string, port string, enableOutput bool) string {
5355 return ip
5456}
5557
58+ func GetFastIPCache () string {
59+ fastIPCacheMu .RLock ()
60+ defer fastIPCacheMu .RUnlock ()
61+ return FastIpCache
62+ }
63+
64+ func GetFastIPMetaCache () FastIPMeta {
65+ fastIPCacheMu .RLock ()
66+ defer fastIPCacheMu .RUnlock ()
67+ return FastIPMetaCache
68+ }
69+
70+ func SetFastIPCacheState (ip string , meta FastIPMeta ) {
71+ fastIPCacheMu .Lock ()
72+ FastIpCache = ip
73+ FastIPMetaCache = meta
74+ fastIPCacheMu .Unlock ()
75+ }
76+
5677func GetFastIPWithContext (ctx context.Context , domain string , port string , enableOutput bool ) (string , error ) {
5778 if ctx == nil {
5879 ctx = context .Background ()
@@ -61,8 +82,8 @@ func GetFastIPWithContext(ctx context.Context, domain string, port string, enabl
6182 if proxyUrl != nil {
6283 return "api.nxtrace.org" , nil
6384 }
64- if FastIpCache != "" {
65- return FastIpCache , nil
85+ if cachedIP := GetFastIPCache (); cachedIP != "" {
86+ return cachedIP , nil
6687 }
6788
6889 var ips []net.IP
@@ -107,11 +128,12 @@ func GetFastIPWithContext(ctx context.Context, domain string, port string, enabl
107128 result .IP = defaultFastIP ()
108129 }
109130
110- FastIPMetaCache = FastIPMeta {
131+ meta : = FastIPMeta {
111132 IP : result .IP ,
112133 Latency : result .Latency ,
113134 NodeName : strings .TrimSpace (result .Content ),
114135 }
136+ SetFastIPCacheState (result .IP , meta )
115137
116138 if enableOutput && ! SuppressFastIPOutput {
117139 _ , _ = fmt .Fprintf (color .Output , "%s preferred API IP - %s - %s - %s" ,
@@ -122,7 +144,6 @@ func GetFastIPWithContext(ctx context.Context, domain string, port string, enabl
122144 )
123145 }
124146
125- FastIpCache = result .IP
126147 return result .IP , nil
127148}
128149
0 commit comments