This commit is contained in:
lzf
2025-03-31 15:25:24 +08:00
26 changed files with 2865 additions and 910 deletions

View File

@@ -1,9 +1,14 @@
package mycommon
import (
"errors"
"git.makemake.in/kzkzzzz/mycommon/mylog"
"log"
"math/rand/v2"
"net"
"os"
"runtime/debug"
"sync"
)
func SafeFn(fn func()) {
@@ -26,3 +31,62 @@ func SafeGo(fn func()) {
func RandRange(min, max int) int {
return rand.IntN(max+1-min) + min
}
var (
getIpOnce = &sync.Once{}
outBoundIp = "127.0.0.1"
)
// GetOutboundIP 获取本机ip
func GetOutboundIP() string {
getIpOnce.Do(func() {
conn, err := net.Dial("udp", "223.5.5.5:53")
if err != nil {
log.Printf("get outbound ip err: %s", err)
return
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
if localAddr.IP != nil {
outBoundIp = localAddr.IP.String()
}
})
return outBoundIp
}
var (
getHostNameOnce = &sync.Once{}
hostName = "unknown"
)
// GetHostName 获取hostname
func GetHostName() string {
getHostNameOnce.Do(func() {
v, err := os.Hostname()
if err != nil {
log.Printf("get host name err: %s", err)
return
}
hostName = v
})
return hostName
}
func ExistFile(file string) bool {
_, err := os.Stat(file)
if err == nil {
return true
}
if errors.Is(err, os.ErrNotExist) {
return false
}
// 其他错误
return false
}