From 44111ae6591e2c770752e8b09206e1ead2bf717a Mon Sep 17 00:00:00 2001 From: smail Date: Sun, 18 Oct 2026 13:22:19 +0800 Subject: [PATCH] =?UTF-8?q?fix(id):=20=E4=BD=BF=E7=94=A8sync.Once=E4=B8=8E?= =?UTF-8?q?sync.RWMutex=E6=B6=88=E9=99=A4getLocalIP=E5=B9=B6=E5=8F=91?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E7=AB=9E=E4=BA=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/utils/id/logid.go | 44 +++++++++++++++++++--------------- backend/utils/id/logid_test.go | 31 ++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 19 deletions(-) create mode 100644 backend/utils/id/logid_test.go diff --git a/backend/utils/id/logid.go b/backend/utils/id/logid.go index d49053df..9e090a6d 100644 --- a/backend/utils/id/logid.go +++ b/backend/utils/id/logid.go @@ -7,32 +7,38 @@ import ( "fmt" "net" "os" + "sync" "time" ) -var ip_instance string +var ( + ipInstance string + ipOnce sync.Once + ipMu sync.RWMutex +) func getLocalIP() string { - if ip_instance != "" { - return ip_instance - } - - ip := "127.0.0.1" - addrs, err := net.InterfaceAddrs() - if err != nil { - ip_instance = ip - return ip - } - for _, a := range addrs { - if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { - if ipnet.IP.To4() != nil { - ip = ipnet.IP.String() - break + ipOnce.Do(func() { + ip := "127.0.0.1" + addrs, err := net.InterfaceAddrs() + if err == nil { + for _, a := range addrs { + if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { + if ipnet.IP.To4() != nil { + ip = ipnet.IP.String() + break + } + } } } - } - ip_instance = ip - return ip + ipMu.Lock() + ipInstance = ip + ipMu.Unlock() + }) + + ipMu.RLock() + defer ipMu.RUnlock() + return ipInstance } func GenLogID() string { diff --git a/backend/utils/id/logid_test.go b/backend/utils/id/logid_test.go new file mode 100644 index 00000000..9f576a91 --- /dev/null +++ b/backend/utils/id/logid_test.go @@ -0,0 +1,31 @@ +package id + +import ( + "sync" + "testing" +) + +func TestGetLocalIPConcurrent(t *testing.T) { + const goroutines = 50 + const iterations = 100 + var wg sync.WaitGroup + wg.Add(goroutines) + + for i := 0; i < goroutines; i++ { + go func() { + defer wg.Done() + for j := 0; j < iterations; j++ { + ip := getLocalIP() + if ip == "" { + t.Errorf("getLocalIP returned empty") + } + logID := GenLogID() + if logID == "" { + t.Errorf("GenLogID returned empty") + } + } + }() + } + + wg.Wait() +}