diff --git a/common/utils.go b/common/utils.go index 28820e4..99101c2 100644 --- a/common/utils.go +++ b/common/utils.go @@ -2,13 +2,17 @@ package common import ( "bytes" + "encoding/hex" "encoding/json" + "errors" "fmt" "io/ioutil" + "net" "os" "path" "path/filepath" "runtime" + "strconv" "strings" "time" @@ -49,10 +53,43 @@ func PanicIf(cond bool, err error) { } } -func GenGid() string { +func getOneHexIp() string { + addrs, err := net.InterfaceAddrs() + if err != nil { + fmt.Printf("cannot get ip, default to another call") + return gNode.Generate().Base58() + } + for _, address := range addrs { + if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { + if ipnet.IP.To4() != nil { + ip := ipnet.IP.To4().String() + ns := strings.Split(ip, ".") + r := []byte{} + for _, n := range ns { + r = append(r, byte(MustAtoi(n))) + } + return hex.EncodeToString(r) + } + + } + } + fmt.Printf("none ipv4, default to another call") return gNode.Generate().Base58() } +// MustAtoi 走must逻辑 +func MustAtoi(s string) int { + r, err := strconv.Atoi(s) + if err != nil { + E2P(errors.New("convert to int error: " + s)) + } + return r +} + +func GenGid() string { + return getOneHexIp() + "-" + gNode.Generate().Base58() +} + var gNode *snowflake.Node = nil func init() { @@ -226,7 +263,6 @@ func GetCurrentDir() string { func GetProjectDir() string { _, file, _, _ := runtime.Caller(1) for ; !strings.HasSuffix(file, "/dtm"); file = filepath.Dir(file) { - } return file } diff --git a/common/utils_test.go b/common/utils_test.go index 50a9128..1c92d23 100644 --- a/common/utils_test.go +++ b/common/utils_test.go @@ -5,7 +5,6 @@ import ( "io" "net/http" "net/http/httptest" - "path/filepath" "strings" "testing" @@ -94,8 +93,3 @@ func TestResty(t *testing.T) { }) assert.NotEqual(t, nil, err2) } - -func TestCaller(t *testing.T) { - p := GetProjectDir() - assert.Equal(t, true, strings.HasSuffix(filepath.Dir(p), "common")) -}