update golang common code.

This commit is contained in:
kaichao 2023-09-28 22:22:42 +08:00
parent fbd642e65a
commit a324ed41a4
4 changed files with 201 additions and 0 deletions

16
golang/misc/init.go Normal file
View File

@ -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)
}

76
golang/misc/net.go Normal file
View File

@ -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
}

14
golang/misc/sql.go Normal file
View File

@ -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,
}
}

View File

@ -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
}