From 7515bea77aaf07a4782b127994c4d583832aff48 Mon Sep 17 00:00:00 2001 From: yzy613 Date: Sun, 22 Oct 2023 15:24:19 +0800 Subject: [PATCH] perf: some logics --- .github/workflows/go.yml | 5 ++- cmd/ddns-watchdog-client/main.go | 6 ++-- internal/client/cloudflare.go | 4 +-- internal/client/public.go | 47 ++++++++++++------------ internal/common/common.go | 61 +++++++++++++++++--------------- internal/common/common_test.go | 57 +++++++++++++++++++++++++++++ internal/server/handler.go | 2 +- internal/server/public.go | 2 +- 8 files changed, 125 insertions(+), 59 deletions(-) create mode 100644 internal/common/common_test.go diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index ec6013b..1a40154 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -10,7 +10,7 @@ on: jobs: build: runs-on: ubuntu-latest - if: +# if: steps: - name: Load repo uses: actions/checkout@v3 @@ -22,6 +22,9 @@ jobs: with: go-version: "1.21" + - name: Test + run: go test ./... + - name: Build client run: make -f Makefile.client diff --git a/cmd/ddns-watchdog-client/main.go b/cmd/ddns-watchdog-client/main.go index 7e17c5c..a12f0f2 100644 --- a/cmd/ddns-watchdog-client/main.go +++ b/cmd/ddns-watchdog-client/main.go @@ -67,9 +67,9 @@ func processFlag() (exit bool, err error) { flag.Parse() // 打印网卡信息 if *printNetworkCardInfo { - ncr, err2 := client.NetworkCardRespond() - if err2 != nil { - err = err2 + var ncr map[string]string + ncr, err = client.NetworkCardRespond() + if err != nil { return } var arr []string diff --git a/internal/client/cloudflare.go b/internal/client/cloudflare.go index 15e0bfc..f22fd23 100644 --- a/internal/client/cloudflare.go +++ b/internal/client/cloudflare.go @@ -115,8 +115,8 @@ func (cfc *Cloudflare) getParseRecord(domain, recordType string) (domainId, reco if err != nil { return } - if err2 := jsonObj.Get("error").MustString(); err2 != "" { - err = errors.New("Cloudflare: " + err2) + if errMsg := jsonObj.Get("error").MustString(); errMsg != "" { + err = errors.New("Cloudflare: " + errMsg) return } if !jsonObj.Get("success").MustBool() { diff --git a/internal/client/public.go b/internal/client/public.go index 0a40d7f..8eb3563 100644 --- a/internal/client/public.go +++ b/internal/client/public.go @@ -91,15 +91,16 @@ func NetworkCardRespond() (map[string]string, error) { } for _, i := range interfaces { - ipAddr, err2 := i.Addrs() - if err2 != nil { - return nil, err2 + var ipAddr []net.Addr + ipAddr, err = i.Addrs() + if err != nil { + return nil, err } for j, addrAndMask := range ipAddr { // 分离 IP 和子网掩码 addr := strings.Split(addrAndMask.String(), "/")[0] if strings.Contains(addr, ":") { - addr = common.DecodeIPv6(addr) + addr = common.ExpandIPv6Zero(addr) } networkCardInfo[i.Name+" "+strconv.Itoa(j)] = addr } @@ -108,7 +109,7 @@ func NetworkCardRespond() (map[string]string, error) { } func GetOwnIP(enabled common.Enable, apiUrl apiUrl, nc networkCard) (ipv4, ipv6 string, err error) { - ncr := make(map[string]string) + var ncr map[string]string // 若需网卡信息,则获取网卡信息并提供给用户 if nc.Enable && nc.IPv4 == "" && nc.IPv6 == "" { ncr, err = NetworkCardRespond() @@ -136,8 +137,9 @@ func GetOwnIP(enabled common.Enable, apiUrl apiUrl, nc networkCard) (ipv4, ipv6 if enabled.IPv4 { // 启用网卡 IPv4 if nc.Enable && nc.IPv4 != "" { - ipv4 = ncr[nc.IPv4] - if ipv4 == "" { + if v, ok := ncr[nc.IPv4]; ok { + ipv4 = v + } else { err = errors.New("IPv4 选择了不存在的网卡") return } @@ -146,9 +148,9 @@ func GetOwnIP(enabled common.Enable, apiUrl apiUrl, nc networkCard) (ipv4, ipv6 if apiUrl.IPv4 == "" { apiUrl.IPv4 = common.DefaultAPIUrl } - resp, err2 := http.Get(apiUrl.IPv4) - if err2 != nil { - err = err2 + var resp *http.Response + resp, err = http.Get(apiUrl.IPv4) + if err != nil { return } defer func(Body io.ReadCloser) { @@ -157,9 +159,9 @@ func GetOwnIP(enabled common.Enable, apiUrl apiUrl, nc networkCard) (ipv4, ipv6 err = t } }(resp.Body) - recvJson, err2 := io.ReadAll(resp.Body) - if err2 != nil { - err = err2 + var recvJson []byte + recvJson, err = io.ReadAll(resp.Body) + if err != nil { return } var ipInfo common.GetIPResp @@ -179,8 +181,9 @@ func GetOwnIP(enabled common.Enable, apiUrl apiUrl, nc networkCard) (ipv4, ipv6 if enabled.IPv6 { // 启用网卡 IPv6 if nc.Enable && nc.IPv6 != "" { - ipv6 = ncr[nc.IPv6] - if ipv6 == "" { + if v, ok := ncr[nc.IPv6]; ok { + ipv6 = v + } else { err = errors.New("IPv6 选择了不存在的网卡") return } @@ -189,9 +192,9 @@ func GetOwnIP(enabled common.Enable, apiUrl apiUrl, nc networkCard) (ipv4, ipv6 if apiUrl.IPv6 == "" { apiUrl.IPv6 = common.DefaultIPv6APIUrl } - resp, err2 := http.Get(apiUrl.IPv6) - if err2 != nil { - err = err2 + var resp *http.Response + resp, err = http.Get(apiUrl.IPv6) + if err != nil { return } defer func(Body io.ReadCloser) { @@ -200,9 +203,9 @@ func GetOwnIP(enabled common.Enable, apiUrl apiUrl, nc networkCard) (ipv4, ipv6 err = t } }(resp.Body) - recvJson, err2 := io.ReadAll(resp.Body) - if err2 != nil { - err = err2 + var recvJson []byte + recvJson, err = io.ReadAll(resp.Body) + if err != nil { return } var ipInfo common.GetIPResp @@ -213,7 +216,7 @@ func GetOwnIP(enabled common.Enable, apiUrl apiUrl, nc networkCard) (ipv4, ipv6 ipv6 = ipInfo.IP } if strings.Contains(ipv6, ":") { - ipv6 = common.DecodeIPv6(ipv6) + ipv6 = common.ExpandIPv6Zero(ipv6) } else { err = errors.New("获取到的 IPv6 格式错误,意外获取到了 " + ipv6) return diff --git a/internal/common/common.go b/internal/common/common.go index 6225ea3..d2f9610 100644 --- a/internal/common/common.go +++ b/internal/common/common.go @@ -3,6 +3,7 @@ package common import ( "encoding/json" "fmt" + "net" "os" "path/filepath" "runtime" @@ -73,11 +74,11 @@ func IsWindows() bool { func IsDirExistAndCreate(dirPath string) (err error) { _, err = os.Stat(dirPath) - if err != nil || os.IsNotExist(err) { - err = os.MkdirAll(dirPath, 0750) - if err != nil { - return err + if err != nil { + if os.IsNotExist(err) { + err = os.MkdirAll(dirPath, 0750) } + return } return } @@ -131,34 +132,36 @@ func CompareVersionString(remoteVersion, localVersion string) bool { return false } -func DecodeIPv6(srcIP string) (dstIP string) { - if strings.Contains(srcIP, "::") { - splitArr := strings.Split(srcIP, "::") - decode := "" - switch { - case srcIP == "::": - dstIP = "0:0:0:0:0:0:0:0" - case splitArr[0] == "" && splitArr[1] != "": - for i := 0; i < 8-len(strings.Split(splitArr[1], ":")); i++ { - decode = "0:" + decode - } - dstIP = decode + splitArr[1] - case splitArr[0] != "" && splitArr[1] == "": - for i := 0; i < 8-len(strings.Split(splitArr[0], ":")); i++ { - decode = decode + ":0" - } - dstIP = splitArr[0] + decode - default: - for i := 0; i < 8-len(strings.Split(splitArr[0], ":"))-len(strings.Split(splitArr[1], ":")); i++ { - decode = decode + ":0" +func ExpandIPv6Zero(ip string) string { + p := net.ParseIP(ip) + if p == nil || p.To4() != nil || len(p) != net.IPv6len { + return ip + } + + const maxLen = len("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff") + b := make([]byte, 0, maxLen) + + const hexDigit = "0123456789abcdef" + appendHex := func(dst []byte, i uint) []byte { + if i == 0 { + return append(dst, '0') + } + for j := 7; j >= 0; j-- { + v := i >> uint(j*4) + if v > 0 { + dst = append(dst, hexDigit[v&0xf]) } - decode = decode + ":" - dstIP = splitArr[0] + decode + splitArr[1] } - } else { - dstIP = srcIP + return dst } - return + + for i := 0; i < net.IPv6len; i += 2 { + if i > 0 { + b = append(b, ':') + } + b = appendHex(b, (uint(p[i])<<8)|uint(p[i+1])) + } + return string(b) } func VersionTips(LatestVersion string) { diff --git a/internal/common/common_test.go b/internal/common/common_test.go new file mode 100644 index 0000000..c9f195b --- /dev/null +++ b/internal/common/common_test.go @@ -0,0 +1,57 @@ +package common + +import "testing" + +func TestExpandIPv6Zero(t *testing.T) { + type args struct { + ip string + } + tests := []struct { + name string + args args + want string + }{ + { + name: "::", + args: args{ + ip: "::", + }, + want: "0:0:0:0:0:0:0:0", + }, + { + name: "::1", + args: args{ + ip: "::1", + }, + want: "0:0:0:0:0:0:0:1", + }, + { + name: "1::", + args: args{ + ip: "1::", + }, + want: "1:0:0:0:0:0:0:0", + }, + { + name: "1::1", + args: args{ + ip: "1::1", + }, + want: "1:0:0:0:0:0:0:1", + }, + { + name: "2001:db8:85a3::8a2e:370:7334", + args: args{ + ip: "2001:db8:85a3::8a2e:370:7334", + }, + want: "2001:db8:85a3:0:0:8a2e:370:7334", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := ExpandIPv6Zero(tt.args.ip); got != tt.want { + t.Errorf("ExpandIPv6Zero() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/internal/server/handler.go b/internal/server/handler.go index cc9a91c..0b3114e 100644 --- a/internal/server/handler.go +++ b/internal/server/handler.go @@ -103,5 +103,5 @@ func RespCenterReq(w http.ResponseWriter, req *http.Request) { } // 访问成功日志 - log.Printf("%v(%v) access success.\n", whitelist[body.Token].Description, GetClientIP(req)) + log.Printf("%v(%v) access successful.\n", whitelist[body.Token].Description, GetClientIP(req)) } diff --git a/internal/server/public.go b/internal/server/public.go index 02bace5..7fb8870 100644 --- a/internal/server/public.go +++ b/internal/server/public.go @@ -181,7 +181,7 @@ func GetClientIP(req *http.Request) (ipAddr string) { // IPv6 转格式 和 :: 解压 if strings.Contains(ipAddr, ":") { - ipAddr = common.DecodeIPv6(ipAddr) + ipAddr = common.ExpandIPv6Zero(ipAddr) } return }