From a324ed41a42d56dac9355c2d2d5759b8fc31d54f Mon Sep 17 00:00:00 2001 From: kaichao Date: Thu, 28 Sep 2023 22:22:42 +0800 Subject: [PATCH] update golang common code. --- golang/misc/init.go | 16 ++++++++ golang/misc/net.go | 76 ++++++++++++++++++++++++++++++++++++ golang/misc/sql.go | 14 +++++++ golang/misc/util.go | 95 +++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 201 insertions(+) create mode 100644 golang/misc/init.go create mode 100644 golang/misc/net.go create mode 100644 golang/misc/sql.go diff --git a/golang/misc/init.go b/golang/misc/init.go new file mode 100644 index 0000000..bba332a --- /dev/null +++ b/golang/misc/init.go @@ -0,0 +1,16 @@ +package misc + +import ( + "os" + + "github.com/sirupsen/logrus" +) + +func init() { + level, err := logrus.ParseLevel(os.Getenv("LOG_LEVEL")) + if err != nil { + level = logrus.WarnLevel + } + logrus.SetLevel(level) + logrus.SetReportCaller(true) +} diff --git a/golang/misc/net.go b/golang/misc/net.go new file mode 100644 index 0000000..9de8782 --- /dev/null +++ b/golang/misc/net.go @@ -0,0 +1,76 @@ +package misc + +import ( + "fmt" + "log" + "net" + "os" + "os/exec" + "strings" +) + +// GetLocalIP ... +// hostname -i / -I +func GetLocalIP() string { + // 0=1, 2, 3, .. ,n + localIPIndexStr := os.Getenv("LOCAL_IP_INDEX") + var cmd string + if localIPIndexStr == "" { + cmd = "hostname -i" + } else { + cmd = fmt.Sprintf("hostname -I | awk '{print $%s}'", localIPIndexStr) + } + + out, _ := exec.Command("/bin/bash", "-c", cmd).Output() + localIP := strings.Split(string(out), " ")[0] + // remove '\n' + localIP = strings.Replace(localIP, "\n", "", -1) + if localIP == "" { + log.Printf("get_local_ip error\n") + } + return localIP +} + +// GetLocalIPv4Addr ... +// @Deprecated +func getLocalIPv4Addr() string { + addrs, err := net.InterfaceAddrs() + if err != nil { + fmt.Println(err) + } + var ip string + for _, address := range addrs { + if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { + if ipnet.IP.To4() != nil { + ip = ipnet.IP.String() + } + } + } + return ip +} + +// GetLocalIPv4AddrByInterface ... +// @Deprecated +func getLocalIPv4AddrByInterface(interfaceName string) string { + interfaces, err := net.Interfaces() + if err != nil { + panic(err) + } + var ip string + for _, interf := range interfaces { + if interf.Name == "en7" { + addrs, err := interf.Addrs() + if err != nil { + panic(err) + } + for _, add := range addrs { + if ipnet, ok := add.(*net.IPNet); ok { + if ipnet.IP.To4() != nil { + ip = ipnet.IP.String() + } + } + } + } + } + return ip +} diff --git a/golang/misc/sql.go b/golang/misc/sql.go new file mode 100644 index 0000000..a5311d7 --- /dev/null +++ b/golang/misc/sql.go @@ -0,0 +1,14 @@ +package misc + +import "database/sql" + +// NewSQLNullString ... +func NewSQLNullString(s string) sql.NullString { + if len(s) == 0 { + return sql.NullString{} + } + return sql.NullString{ + String: s, + Valid: true, + } +} diff --git a/golang/misc/util.go b/golang/misc/util.go index d7304f2..6bd8716 100644 --- a/golang/misc/util.go +++ b/golang/misc/util.go @@ -3,7 +3,14 @@ package misc import ( "bufio" "fmt" + "io/ioutil" "os" + "os/exec" + "reflect" + "runtime" + "strings" + + "github.com/sirupsen/logrus" ) // AppendToFile ... @@ -20,3 +27,91 @@ func AppendToFile(fileName string, line string) { writer.WriteString(line + "\n") writer.Flush() } + +// ExecShellCommand ... +// +// return stdout +// +// func ExecShellCommand(cmdText string) { +// cmd := exec.Command("bash", "-c", cmdText) +// if out, err := cmd.Output(); err != nil { +// fmt.Fprintln(os.Stderr, err) +// } else { +// fmt.Println(string(out)) +// } +// } +func ExecShellCommand(myCmd string) string { + cmd := exec.Command("bash", "-c", myCmd) + output, err := cmd.Output() + logrus.Infof("IN execCmd(), cmd=%s,stdout=%s\n", myCmd, string(output)) + if err != nil { + logrus.Errorf("ERROR in execCmd(): cmd=%s,err=%v\n", myCmd, err) + return "" + } + // 删除尾部的\n + return strings.Replace(string(output), "\n", "", -1) +} + +// GetTextFileLines ... +func GetTextFileLines(textFile string) ([]string, error) { + if _, err := os.Stat(textFile); err != nil { + return []string{}, nil + } + + fileContent, err := ioutil.ReadFile(textFile) + if err != nil { + return []string{}, fmt.Errorf("Read file error, filename:%s, err:%v", textFile, err) + } + var lines []string + for _, line := range strings.Split(string(fileContent), "\n") { + if strings.TrimSpace(line) != "" { + lines = append(lines, line) + } + } + return lines, nil +} + +// SplitCommaWithEscapeSupport .. +func SplitCommaWithEscapeSupport(s string) []string { + var ret []string + i0 := 0 + i := 0 + for ; i < len(s); i++ { + if s[i] == ',' && i > 0 && s[i-1] != '\\' { + ret = append(ret, strings.ReplaceAll(s[i0:i], "\\,", ",")) + i0 = i + 1 + } + } + if i0 < i { + ret = append(ret, strings.ReplaceAll(s[i0:i], "\\,", ",")) + } + return ret +} + +// GetFunctionName ... +func GetFunctionName(i interface{}, seps ...rune) string { + fn := runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name() + + fields := strings.FieldsFunc(fn, func(sep rune) bool { + for _, s := range seps { + if sep == s { + return true + } + } + return false + }) + + if size := len(fields); size > 0 { + return fields[size-1] + } + return "" +} + +// IsRunnable ... +func IsRunnable(runFile string) bool { + stat, err := os.Stat(runFile) + if err != nil { + return false + } + return stat.Mode()&0111 != 0 +}