@ -0,0 +1,63 @@ | |||
package helper | |||
import ( | |||
"net/http" | |||
"strings" | |||
) | |||
/** | |||
* 取访问主机名 | |||
*/ | |||
func GetHost(req *http.Request) string { | |||
var hostlist []string = req.Header.Values("X-Forwarded-Host") | |||
var host string | |||
if len(hostlist) > 1 { | |||
host = hostlist[len(hostlist)-1] //取最后一次转发的 | |||
} else if len(hostlist) == 1 { | |||
host = hostlist[0] | |||
} else { | |||
host = "" | |||
} | |||
if host != "" { | |||
hosts := strings.Split(host, ",") | |||
host = strings.Trim(hosts[len(hosts)-1], " ") | |||
} | |||
if host == "" { | |||
host = req.Host | |||
} | |||
return host | |||
} | |||
/** | |||
* 取域名 | |||
*/ | |||
func GetDomain(req *http.Request) string { | |||
scheme := "http://" | |||
if req.TLS != nil { | |||
scheme = "https://" | |||
} | |||
if strings.Contains(req.Referer(), "https://") { | |||
scheme = "https://" | |||
} | |||
var host string = GetHost(req) | |||
host = strings.Split(host, ":")[0] | |||
var w strings.Builder | |||
w.WriteString(scheme) | |||
w.WriteString(host) | |||
return w.String() | |||
} | |||
func SetHeader(w http.ResponseWriter, resp *http.Request) { | |||
w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域 | |||
w.Header().Add("Access-Control-Allow-Headers", "Content-Type,x-csrf-token,x-requested-with,token") //header的类型 | |||
w.Header().Set("Access-Control-Allow-Methods", "POST,GET,OPTIONS") | |||
w.Header().Set("content-type", "application/json") //返回数据格式是json | |||
// w.Header().Set("Content-Length", resp.Header.Get("Content-Length")) | |||
} |
@ -0,0 +1,63 @@ | |||
package helper | |||
import ( | |||
"errors" | |||
) | |||
func MergeStringMap(x, y map[string]string) map[string]string { | |||
n := make(map[string]string) | |||
for i, v := range x { | |||
for j, w := range y { | |||
if i == j { | |||
n[i] = w | |||
} else { | |||
if _, ok := n[i]; !ok { | |||
n[i] = v | |||
} | |||
if _, ok := n[j]; !ok { | |||
n[j] = w | |||
} | |||
} | |||
} | |||
} | |||
return n | |||
} | |||
/** | |||
* 转换为map string数组 | |||
* 2021/1/5 | |||
* gz | |||
*/ | |||
func ToMapStringArray(x interface{}) ([]map[string]string, error) { | |||
list, ok := x.([]interface{}) | |||
if !ok { | |||
return []map[string]string{}, errors.New("type error") | |||
} | |||
if len(list) < 1 { | |||
return []map[string]string{}, nil | |||
} | |||
var ret []map[string]string = make([]map[string]string, len(list)) | |||
var tmp map[string]interface{} | |||
var map_tmp map[string]string | |||
var err error | |||
for key, item := range list { | |||
if tmp, ok = item.(map[string]interface{}); ok { | |||
map_tmp = make(map[string]string) | |||
for k, v := range tmp { | |||
map_tmp[k] = ToStr(v) | |||
} | |||
ret[key] = map_tmp | |||
} else { | |||
err = errors.New("data type error") | |||
break | |||
} | |||
} | |||
return ret, err | |||
} |
@ -0,0 +1,131 @@ | |||
package helper | |||
import ( | |||
"fmt" | |||
"math/big" | |||
"strconv" | |||
) | |||
//字节自动转换为B/KB/MB/GB | |||
func ByteToUnitSize(Size interface{}) (float64, string) { | |||
var unit string | |||
var iFloat, mb, gb float64 = 0, 1024, 1024 * 1024 | |||
iSize, _ := ToFloat64(Size) | |||
rSize := iSize / 1024 | |||
if rSize >= 0 && rSize < 1 { | |||
iFloat, unit = iSize, "B" | |||
} else if rSize >= 1 && rSize < mb { | |||
iFloat, unit = rSize, "KB" | |||
} else if rSize >= mb && rSize < gb { | |||
iFloat, unit = rSize/1024, "MB" | |||
} else if rSize >= gb { | |||
iFloat, unit = rSize/1024/1024, "GB" | |||
} | |||
return iFloat, unit | |||
} | |||
/** | |||
* 数值相加 | |||
* @param str 加数,加数... | |||
* 2020/05/22 | |||
* gz | |||
*/ | |||
func FloatAdd(str ...interface{}) float64 { | |||
length := len(str) | |||
if length < 1 { | |||
return 0 | |||
} | |||
var i int = 0 | |||
var result, tmp float64 = 0, 0 | |||
var err error | |||
for i < length { | |||
tmp, err = ToFloat64(str[i]) | |||
if err == nil { | |||
result, _ = new(big.Float).Add(new(big.Float).SetFloat64(result), new(big.Float).SetFloat64(tmp)).Float64() | |||
} | |||
i++ | |||
} | |||
result, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", result), 64) | |||
return result | |||
} | |||
/** | |||
* float相减 | |||
* @param str 被减数,减数... | |||
* 2020/05/22 | |||
* gz | |||
*/ | |||
func FloatSub(str ...interface{}) float64 { | |||
length := len(str) | |||
if length < 1 { | |||
return 0 | |||
} | |||
var i int = 1 | |||
result, err := ToFloat64(str[0]) | |||
var tmp float64 = 0 | |||
for i < length { | |||
tmp, err = ToFloat64(str[i]) | |||
if err == nil { | |||
result, _ = new(big.Float).Sub(new(big.Float).SetFloat64(result), new(big.Float).SetFloat64(tmp)).Float64() | |||
} | |||
i++ | |||
} | |||
result, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", result), 64) | |||
return result | |||
} | |||
/** | |||
* float相乘 | |||
* @param str 被除数,除数,保留小数位数 | |||
* 2020/05/25 | |||
* gz | |||
*/ | |||
func FloatMul(str ...interface{}) float64 { | |||
if len(str) < 2 { | |||
return 0 | |||
} | |||
places := "2" //默认两位小数 | |||
if len(str) > 2 { | |||
places = ToString(str[2]) | |||
} | |||
float_1, _ := ToFloat64(str[0]) | |||
float_2, _ := ToFloat64(str[1]) | |||
ret, _ := new(big.Float).Mul(new(big.Float).SetFloat64(float_1), new(big.Float).SetFloat64(float_2)).Float64() | |||
ret, _ = strconv.ParseFloat(fmt.Sprintf("%."+places+"f", ret), 64) | |||
return ret | |||
} | |||
/** | |||
* float相除 | |||
* @param str 被除数,除数,保留小数位数 | |||
* 2020/05/25 | |||
* gz | |||
*/ | |||
func FloatQuo(str ...interface{}) float64 { | |||
if len(str) < 2 { | |||
return 0 | |||
} | |||
places := "2" //默认两位小数 | |||
if len(str) > 2 { | |||
places = ToString(str[2]) | |||
} | |||
float_1, _ := ToFloat64(str[0]) | |||
float_2, _ := ToFloat64(str[1]) | |||
if float_2 <= 0 { | |||
return 0 | |||
} | |||
ret, _ := new(big.Float).Quo(new(big.Float).SetFloat64(float_1), new(big.Float).SetFloat64(float_2)).Float64() | |||
ret, _ = strconv.ParseFloat(fmt.Sprintf("%."+places+"f", ret), 64) | |||
return ret | |||
} |
@ -0,0 +1,44 @@ | |||
package helper | |||
import ( | |||
"strings" | |||
"testing" | |||
) | |||
func Test_FloadAdd(t *testing.T) { | |||
// str1 := 4 | |||
str2 := "5" | |||
str3 := 6.5 | |||
// str4 := 1 | |||
ret := FloatAdd(str3, str2) | |||
t.Log(ret) | |||
percentage := "8:2:1" | |||
price := strings.Split(percentage, ":") | |||
ret = FloatAdd(price[0], price[1], price[2]) | |||
t.Log(ret) | |||
} | |||
func Test_FloatSub(t *testing.T) { | |||
str1 := 4.25 | |||
str2 := "5.33" | |||
ret := FloatSub(str1, str2) | |||
t.Log(ret) | |||
} | |||
func Test_FloatMul(t *testing.T) { | |||
str1 := 4.25 | |||
str2 := "5.33" | |||
ret := FloatMul(str1, str2, 1) | |||
t.Log(ret) | |||
} | |||
func Test_FloatQuo(t *testing.T) { | |||
str1 := 6 | |||
str2 := "7" | |||
ret := FloatQuo(str1, str2, 3) | |||
t.Log(ret) | |||
} |
@ -0,0 +1,48 @@ | |||
package helper | |||
import ( | |||
"strings" | |||
) | |||
/** | |||
* 处理传递的参数 | |||
* @param param | |||
* @return | |||
* 2020/05/15 | |||
* gz | |||
*/ | |||
func ParamsString(param string) string { | |||
if strings.Contains(param, " ") { | |||
return "" | |||
} | |||
return param | |||
} | |||
/** | |||
* 根据第几页计算从第几行开始 | |||
* @param pageNum 第几页 | |||
* @param pageSize 每页几行 | |||
* @return from,offset 开始行数,偏移量 | |||
* 2020/05/15 | |||
* gz | |||
*/ | |||
func GetPage(pageNum, pageSize interface{}) (string, string) { | |||
var from string | |||
var offset int = ToInt(pageSize) | |||
var pageNumInt, pageSizeInt int = ToInt(pageNum), ToInt(pageSize) | |||
if pageNumInt < 1 { | |||
pageNumInt = 1 | |||
} | |||
if pageSizeInt < 1 { | |||
offset = 10 | |||
pageSizeInt = 10 | |||
} | |||
from = ToString((pageNumInt - 1) * pageSizeInt) | |||
return from, ToString(offset) | |||
} |
@ -0,0 +1,13 @@ | |||
package helper | |||
import ( | |||
"testing" | |||
) | |||
func Test_GetPage(t *testing.T) { | |||
// var page, page_size string = "0", "10" | |||
from, offset := GetPage(2, 10) | |||
t.Log(from) | |||
t.Log(offset) | |||
} |
@ -0,0 +1,252 @@ | |||
/* | |||
* string functions | |||
*/ | |||
package helper | |||
import ( | |||
"errors" | |||
"fmt" | |||
"log" | |||
"math/rand" | |||
"regexp" | |||
"strconv" | |||
"strings" | |||
"time" | |||
) | |||
func ToString(v interface{}) string { | |||
var value string | |||
switch v.(type) { | |||
case string: | |||
value = v.(string) | |||
case int: | |||
value = strconv.Itoa(v.(int)) | |||
case float64: | |||
value = strconv.FormatFloat(v.(float64), 'f', 2, 64) | |||
case float32: | |||
value = strconv.FormatFloat(float64(v.(float32)), 'f', 2, 64) | |||
case int64: | |||
value = strconv.FormatInt(v.(int64), 10) | |||
case []uint8: | |||
value = string(v.([]uint8)) | |||
// case []byte: | |||
// value = string(v.([]byte)) | |||
case interface{}: | |||
value = v.(string) | |||
case nil: | |||
value = "" | |||
default: | |||
log.Println("参数值类型错误", v, "not in string|int|float64|interface|int64") | |||
} | |||
return strings.Trim(value, " ") | |||
} | |||
func ToStr(v interface{}) string { | |||
var value string | |||
switch v.(type) { | |||
case string: | |||
value = v.(string) | |||
case int: | |||
value = strconv.Itoa(v.(int)) | |||
case float64: | |||
value = strconv.FormatFloat(v.(float64), 'f', 0, 64) | |||
case float32: | |||
value = strconv.FormatFloat(float64(v.(float32)), 'f', 0, 64) | |||
case int64: | |||
value = strconv.FormatInt(v.(int64), 10) | |||
case []uint8: | |||
value = string(v.([]uint8)) | |||
// case []byte: | |||
// value = string(v.([]byte)) | |||
case interface{}: | |||
value = v.(string) | |||
case nil: | |||
value = "" | |||
default: | |||
log.Println("参数值类型错误", v, "not in string|int|float64|interface|int64") | |||
} | |||
return strings.Trim(value, " ") | |||
} | |||
func ToFloat64(v interface{}) (float64, error) { | |||
var value float64 | |||
var err error = nil | |||
switch v.(type) { | |||
case string: | |||
v_tmp := v.(string) | |||
value, _ = strconv.ParseFloat(v_tmp, 64) | |||
case int: | |||
value = float64(v.(int)) | |||
case int64: | |||
value = float64(v.(int64)) | |||
case float64: | |||
value = v.(float64) | |||
case interface{}: | |||
value = v.(float64) | |||
case nil: | |||
value = 0 | |||
default: | |||
err = errors.New("参数值类型错误") | |||
log.Println("参数值类型错误", v, "not in string|int|float64|interface|int64") | |||
} | |||
return value, err | |||
} | |||
func ToInt(inter interface{}) int { | |||
var value int | |||
switch inter.(type) { | |||
case string: | |||
value, _ = strconv.Atoi(inter.(string)) | |||
case int: | |||
value = inter.(int) | |||
case int64: | |||
value = int(inter.(int64)) | |||
case float64: | |||
value, _ = strconv.Atoi(fmt.Sprintf("%1.0f", inter)) | |||
case nil: | |||
value = 0 | |||
case interface{}: | |||
value = inter.(int) | |||
default: | |||
log.Println("参数值类型错误", inter, "not in string|int|float64|interface|int64") | |||
} | |||
return value | |||
} | |||
func ToInt64(inter interface{}) int64 { | |||
var value int64 | |||
switch inter.(type) { | |||
case string: | |||
value, _ = strconv.ParseInt(inter.(string), 10, 64) | |||
case int: | |||
value = int64(inter.(int)) | |||
case int64: | |||
value = inter.(int64) | |||
case float64: | |||
value_int, _ := strconv.Atoi(fmt.Sprintf("%1.0f", inter)) | |||
value = int64(value_int) | |||
case nil: | |||
value = 0 | |||
case interface{}: | |||
if _, ok := inter.(int64); !ok { | |||
value = inter.(int64) | |||
} | |||
default: | |||
log.Println("参数值类型错误", inter, "not in string|int|float64|interface|int64") | |||
} | |||
return value | |||
} | |||
//生成随机字符串 | |||
func GetRandomString(length int) string { | |||
str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" | |||
bytes := []byte(str) | |||
result := []byte{} | |||
r := rand.New(rand.NewSource(time.Now().UnixNano())) | |||
for i := 0; i < length; i++ { | |||
result = append(result, bytes[r.Intn(len(bytes))]) | |||
} | |||
return string(result) | |||
} | |||
//生成随机数字 | |||
func GetRandomNumber(length int) string { | |||
str := "0123456789" | |||
bytes := []byte(str) | |||
result := []byte{} | |||
r := rand.New(rand.NewSource(time.Now().UnixNano())) | |||
for i := 0; i < length; i++ { | |||
result = append(result, bytes[r.Intn(len(bytes))]) | |||
} | |||
return string(result) | |||
} | |||
/** | |||
* 字符串转大驼峰 ios_bbbbbbbb -> IosBbbbbbbbb | |||
*/ | |||
func StrFirstToUpper(str string) string { | |||
temp := strings.Split(str, "_") | |||
var upperStr string | |||
for y := 0; y < len(temp); y++ { | |||
vv := []rune(temp[y]) | |||
for i := 0; i < len(vv); i++ { | |||
if i == 0 { | |||
vv[i] -= 32 | |||
upperStr += string(vv[i]) | |||
} else { | |||
upperStr += string(vv[i]) | |||
} | |||
} | |||
} | |||
return upperStr | |||
} | |||
/** | |||
* 是否存在在字符切片中 | |||
*/ | |||
func IsInStringArray(arr []string, str string) bool { | |||
var isIn bool = false | |||
length := len(arr) | |||
if length < 1 { | |||
return false | |||
} | |||
for _, item := range arr { | |||
if item == str { | |||
isIn = true | |||
break | |||
} | |||
} | |||
return isIn | |||
} | |||
/* | |||
* 删除多余空格 | |||
* 2019/05/05 | |||
*/ | |||
func DeleteExtraSpace(s string) string { | |||
s1 := strings.Replace(s, " ", " ", -1) //替换tab | |||
regstr := "\\s{2,}" //两个及两个以上空格的正则表达式 | |||
reg, _ := regexp.Compile(regstr) //编译正则表达式 | |||
s2 := make([]byte, len(s1)) | |||
copy(s2, s1) | |||
spc_index := reg.FindStringIndex(string(s2)) //在字符串中搜索 | |||
for len(spc_index) > 0 { | |||
s2 = append(s2[:spc_index[0]+1], s2[spc_index[1]:]...) //删除多余空格 | |||
spc_index = reg.FindStringIndex(string(s2)) | |||
} | |||
return string(s2) | |||
} | |||
/* | |||
* 连接多个字符串 | |||
* 2019/05/05 | |||
*/ | |||
func StringJoin(s ...string) string { | |||
var build strings.Builder | |||
if len(s) > 0 { | |||
for _, v := range s { | |||
build.WriteString(v) | |||
} | |||
} | |||
return build.String() | |||
} | |||
/* | |||
* 连接url | |||
* 2019/05/05 | |||
*/ | |||
func UrlJoin(host, url string) string { | |||
if strings.Contains(url, "http://") { | |||
return url | |||
} | |||
if strings.Contains(url, "https://") { | |||
return url | |||
} | |||
return StringJoin(host, url) | |||
} |
@ -0,0 +1,48 @@ | |||
package helper | |||
import ( | |||
"testing" | |||
) | |||
func Test_ToInt64(t *testing.T) { | |||
var str interface{} = 45.00 | |||
ret := ToInt64(str) | |||
t.Log(ret) | |||
} | |||
func Test_GetRandomNumber(t *testing.T) { | |||
rand := GetRandomNumber(8) | |||
fmt.Println(rand) | |||
} | |||
func Test_GetRandomString(t *testing.T) { | |||
rand := GetRandomString(25) | |||
fmt.Println(rand) | |||
} | |||
func Test_DeleteExtraSpace(t *testing.T) { | |||
s := "c s dfdf dff df x" | |||
s2 := DeleteExtraSpace(s) | |||
t.Log(s2) | |||
} | |||
func Test_StringJoin(t *testing.T) { | |||
s1 := "testing" | |||
s2 := "测试一" | |||
s3 := "二" | |||
s4 := " ,s e" | |||
fmt.Println(StringJoin(s1, s2, s3, s4)) | |||
} | |||
func Test_ToString(t *testing.T) { | |||
var str float64 = 0.15 | |||
t.Log(str) | |||
ret := ToString(str) | |||
t.Log(ret) | |||
} | |||
func Test_ToInt(t *testing.T) { | |||
var str interface{} = 45 | |||
ret := ToInt(str) | |||
t.Log(ret) | |||
} |
@ -0,0 +1,478 @@ | |||
/* | |||
* System info | |||
*/ | |||
package helper | |||
import ( | |||
"bytes" | |||
"errors" | |||
"fmt" | |||
"io/ioutil" | |||
"log" | |||
"os/exec" | |||
"regexp" | |||
"strconv" | |||
"strings" | |||
) | |||
func CpuUsage() string { | |||
cmd := exec.Command("ps", "aux") | |||
var out bytes.Buffer | |||
cmd.Stdout = &out | |||
err := cmd.Run() | |||
if err != nil { | |||
return "" | |||
} | |||
var all float64 | |||
for { | |||
line, err := out.ReadString('\n') | |||
if err != nil { | |||
break | |||
} | |||
tokens := strings.Split(line, " ") | |||
ft := make([]string, 0) | |||
for _, t := range tokens { | |||
if t != "" && t != "\t" { | |||
ft = append(ft, t) | |||
} | |||
} | |||
if ft[2] == "%CPU" { | |||
continue | |||
} | |||
cpu, err := strconv.ParseFloat(ft[2], 64) | |||
if err != nil { | |||
continue | |||
} | |||
all += cpu | |||
} | |||
return fmt.Sprintf("%.2f", all) | |||
} | |||
/* | |||
* disk usage of path/disk | |||
*/ | |||
//func DiskUsage(path string) map[string]string { | |||
// mDisk := make(map[string]string) | |||
// sFs := syscall.Statfs_t{} | |||
// Err := syscall.Statfs(path, &sFs) | |||
// if Err != nil { | |||
// log.Println("ERROR", "170060|查询磁盘使用情况出错", Err.Error()) | |||
// return mDisk | |||
// } | |||
// All := sFs.Blocks * uint64(sFs.Bsize) / 1024 / 1024 | |||
// Free := sFs.Bfree * uint64(sFs.Bsize) / 1024 / 1024 | |||
// mDisk["All"] = strconv.FormatUint(All, 10) | |||
// mDisk["Free"] = strconv.FormatUint(Free, 10) | |||
// mDisk["Used"] = strconv.FormatUint((All - Free), 10) | |||
// return mDisk | |||
//} | |||
//func MemStat() map[string]string { | |||
// //系统占用,仅linux/mac下有效 | |||
// //system memory usage | |||
// mMem := make(map[string]string) | |||
// sysInfo := new(syscall.Sysinfo_t) | |||
// Err := syscall.Sysinfo(sysInfo) | |||
// if Err == nil { | |||
// All := sysInfo.Totalram / 1024 / 1024 | |||
// Free := sysInfo.Freeram / 1024 / 1024 | |||
// Swap := sysInfo.Totalswap / 1024 / 1024 | |||
// SwapFree := sysInfo.Freeswap / 1024 / 1024 | |||
// mMem["All"] = strconv.FormatUint(All, 10) //* uint64(syscall.Getpagesize()) | |||
// mMem["Free"] = strconv.FormatUint(Free, 10) //* uint64(syscall.Getpagesize()) | |||
// mMem["Used"] = strconv.FormatUint(All-Free, 10) | |||
// mMem["Swap"] = strconv.FormatUint(Swap, 10) | |||
// mMem["SwapFree"] = strconv.FormatUint(SwapFree, 10) | |||
// mMem["SwapUsed"] = strconv.FormatUint(Swap-SwapFree, 10) | |||
// day := sysInfo.Uptime / 86400 | |||
// hour := sysInfo.Uptime % 86400 / 3600 | |||
// minute := sysInfo.Uptime % 86400 % 3600 / 60 | |||
// tTime := time.Now().Unix() - sysInfo.Uptime | |||
// tNow := time.Unix(tTime, 10) | |||
// mMem["StartTime"] = tNow.Format("2006") + "-" + tNow.Format("01") + "-" + tNow.Format("02") + " " + tNow.Format("15") + ":" + tNow.Format("04") + ":" + tNow.Format("05") | |||
// mMem["Runtime"] = strconv.FormatInt(day, 10) + "天" + strconv.FormatInt(hour, 10) + "小时" + strconv.FormatInt(minute, 10) + "分钟" | |||
// | |||
// } else { | |||
// log.Println("ERROR", "170060|查询内存使用情况出错", Err.Error()) | |||
// } | |||
// return mMem | |||
//} | |||
/** | |||
* IO读写 | |||
*/ | |||
func IoUsage() map[string]string { | |||
cmd := exec.Command("iostat") | |||
var out bytes.Buffer | |||
cmd.Stdout = &out | |||
err := cmd.Run() | |||
mIo := make(map[string]string) | |||
if err != nil { | |||
log.Println("ERROR", "170061|系统命令iostat 执行错误", err.Error()) | |||
return mIo | |||
} | |||
for { | |||
line, err := out.ReadString('\n') | |||
if err != nil { | |||
break | |||
} | |||
tokens := strings.Split(line, " ") | |||
ft := make([]string, 0) | |||
for _, t := range tokens { | |||
if t != "" && t != "\t" { | |||
fi := strings.Trim(t, "\n\t") | |||
ft = append(ft, fi) | |||
} | |||
} | |||
if ft[0] == "sda" { | |||
mIo["ReadSpd"] = ft[2] | |||
mIo["WriteSpd"] = ft[3] | |||
mIo["Read"] = ft[4] | |||
mIo["Write"] = ft[5] | |||
} | |||
} | |||
return mIo | |||
} | |||
/** | |||
*文件系统使用率 | |||
*/ | |||
func FileUsage() []interface{} { | |||
cmd := exec.Command("df", "-h") | |||
var out bytes.Buffer | |||
cmd.Stdout = &out | |||
err := cmd.Run() | |||
mList := make([]interface{}, 0) | |||
if err != nil { | |||
log.Println("ERROR", "170061|系统命令df -h执行错误", err.Error()) | |||
return mList | |||
} | |||
var mRet map[string]string | |||
for { | |||
line, err := out.ReadString('\n') | |||
if err != nil { | |||
break | |||
} | |||
tokens := strings.Split(line, " ") | |||
ft := make([]string, 0) | |||
for _, t := range tokens { | |||
if t != "" && t != "\t" { | |||
fi := strings.Trim(t, "\n\t") | |||
ft = append(ft, fi) | |||
} | |||
} | |||
if ft[0] != "Filesystem" { | |||
mRet = make(map[string]string) | |||
mRet["FileSystem"] = ft[0] | |||
mRet["All"] = ft[1] | |||
mRet["Used"] = ft[2] | |||
mRet["Free"] = ft[3] | |||
mRet["UsePercent"] = ft[4] | |||
mRet["Mounted"] = ft[5] | |||
mList = append(mList, mRet) | |||
} | |||
} | |||
return mList | |||
} | |||
/** | |||
*系统负载1 5 10 分钟 | |||
*/ | |||
func LoadAverage() map[string]string { | |||
cmd := exec.Command("uptime") | |||
var out bytes.Buffer | |||
cmd.Stdout = &out | |||
err := cmd.Run() | |||
mRet := make(map[string]string) | |||
if err != nil { | |||
log.Println("ERROR", "170061|系统命令uptime执行错误", err.Error()) | |||
return mRet | |||
} | |||
sLine, err := out.ReadString('\n') | |||
if err != nil { | |||
log.Println("ERROR", "170060|读取系统负载数据出错", err.Error()) | |||
return mRet | |||
} | |||
//正则表达获取1 5 15 分钟系统负载数据 | |||
sRegs := "\\d+\\.\\d+" | |||
sReg := regexp.MustCompile(sRegs) | |||
sLoadAverage := sReg.FindAllString(sLine, 3) | |||
if len(sLoadAverage) >= 3 { | |||
mRet["OneMin"] = sLoadAverage[0] | |||
mRet["FivMin"] = sLoadAverage[1] | |||
mRet["TenfivMin"] = sLoadAverage[2] | |||
} else { | |||
return mRet | |||
} | |||
return mRet | |||
} | |||
/** | |||
*网卡使用情况 | |||
*/ | |||
func NetUsage() []interface{} { | |||
var Net struct { | |||
NetCard string | |||
Rbytes string | |||
Rpackets string | |||
Rerrors string | |||
Rpck string | |||
Sbytes string | |||
Spackets string | |||
Serrors string | |||
Spck string | |||
} | |||
cmd := exec.Command("ifconfig") | |||
var out bytes.Buffer | |||
cmd.Stdout = &out | |||
err := cmd.Run() | |||
aNetList := make([]interface{}, 0) | |||
if err != nil { | |||
log.Println("ERROR", "170060|查询网卡使用情况出错", err.Error()) | |||
return aNetList | |||
} | |||
for { | |||
line, err := out.ReadString('\n') | |||
if err != nil { | |||
break | |||
} | |||
tokens := strings.Split(line, " ") | |||
ft := make([]string, 0) | |||
for _, t := range tokens { | |||
if t != "" && t != "\t" { | |||
fi := strings.Trim(t, "\n\t") | |||
ft = append(ft, fi) | |||
} | |||
} | |||
if ft[0] != "" { | |||
if ft[1] == "Link" { | |||
Net.NetCard = ft[0] | |||
sPck := NetBytes(ft[0]) | |||
if len(sPck) >= 2 { | |||
Net.Rpck = sPck[0] | |||
Net.Spck = sPck[1] | |||
} else { | |||
Net.Rpck = "0.0" | |||
Net.Spck = "0.0" | |||
} | |||
} | |||
if ft[0] == "RX" { | |||
if strings.Contains(ft[1], "packets") { | |||
sPackets := strings.SplitAfter(ft[1], ":") | |||
Net.Rpackets = sPackets[1] | |||
sErrors := strings.SplitAfter(ft[2], ":") | |||
Net.Rerrors = sErrors[1] | |||
} | |||
if strings.Contains(ft[1], "bytes") { | |||
rBytes := strings.SplitAfter(ft[1], ":") | |||
Net.Rbytes = rBytes[1] | |||
sBytes := strings.SplitAfter(ft[5], ":") | |||
Net.Sbytes = sBytes[1] | |||
aNetList = append(aNetList, Net) | |||
} | |||
} | |||
if ft[0] == "TX" { | |||
if strings.Contains(ft[1], "packets") { | |||
sPackets := strings.SplitAfter(ft[1], ":") | |||
Net.Spackets = sPackets[1] | |||
sErrors := strings.SplitAfter(ft[2], ":") | |||
Net.Serrors = sErrors[1] | |||
} | |||
} | |||
} | |||
} | |||
return aNetList | |||
} | |||
/** | |||
*网卡实时流量 | |||
*/ | |||
func NetBytes(Iface string) []string { | |||
aBytesInfo := make([]string, 0) | |||
cmd := exec.Command("sar", "-n", "DEV", "1", "1") | |||
var out bytes.Buffer | |||
cmd.Stdout = &out | |||
err := cmd.Run() | |||
if err != nil { | |||
log.Println("ERROR", "170060|查询实时流量情况出错", err.Error()) | |||
return aBytesInfo | |||
} | |||
for { | |||
line, err := out.ReadString('\n') | |||
if err != nil { | |||
break | |||
} | |||
tokens := strings.Split(line, " ") | |||
ft := make([]string, 0) | |||
for _, t := range tokens { | |||
if t != "" && t != "\t" { | |||
fi := strings.Trim(t, "\n\t") | |||
ft = append(ft, fi) | |||
} | |||
} | |||
if ft[0] == "Average:" { | |||
if ft[1] == Iface { | |||
aBytesInfo = append(aBytesInfo, ft[2]) | |||
aBytesInfo = append(aBytesInfo, ft[3]) | |||
} | |||
} | |||
} | |||
return aBytesInfo | |||
} | |||
/** | |||
*网络配置 | |||
*/ | |||
func GetNetConfig() []interface{} { | |||
aNetCard := make([]interface{}, 0) | |||
cmd := exec.Command("cat", "/etc/network/interfaces") | |||
var out bytes.Buffer | |||
cmd.Stdout = &out | |||
err := cmd.Run() | |||
if err != nil { | |||
log.Println("ERROR", "170050|查询网卡配置信息出错", err.Error()) | |||
return aNetCard | |||
} | |||
var mNetConfig map[string]string | |||
mNetConfig = make(map[string]string) | |||
for { | |||
line, err := out.ReadString('\n') | |||
if err != nil { | |||
break | |||
} | |||
nline := strings.Replace(line, "\t", " ", -1) | |||
tokens := strings.Split(nline, " ") | |||
ft := make([]string, 0) | |||
for _, t := range tokens { | |||
if t != "" { | |||
fi := strings.Trim(t, "\n") | |||
ft = append(ft, fi) | |||
} | |||
} | |||
switch ft[0] { | |||
case "auto": | |||
if len(ft) < 2 { | |||
ft = append(ft, " ") | |||
} | |||
if ft[1] != "lo" { | |||
mNetConfig["NetCard"] = ft[1] | |||
} | |||
case "netmask": | |||
if len(ft) < 2 { | |||
ft = append(ft, " ") | |||
} | |||
mNetConfig["NetMask"] = ft[1] | |||
case "gateway": | |||
if len(ft) < 2 { | |||
ft = append(ft, " ") | |||
} | |||
mNetConfig["GateWay"] = ft[1] | |||
case "address": | |||
if len(ft) < 2 { | |||
ft = append(ft, " ") | |||
} | |||
mNetConfig["Ip"] = ft[1] | |||
case "dns-nameservers": | |||
if len(ft) < 2 { | |||
ft = append(ft, "") | |||
} | |||
mNetConfig["Dns"] = ft[1] | |||
case "dns-nameserver": | |||
if len(ft) < 2 { | |||
ft = append(ft, "") | |||
} | |||
mNetConfig["Dns"] = ft[1] | |||
} | |||
if len(mNetConfig) == 5 { | |||
aNetCard = append(aNetCard, mNetConfig) | |||
mNetConfig = make(map[string]string) | |||
} | |||
} | |||
return aNetCard | |||
} | |||
/** | |||
*修改网络配置 | |||
*/ | |||
func PutNetConfig(mString map[string]string) error { | |||
bFile, err := ioutil.ReadFile("/etc/network/interfaces") | |||
if err != nil { | |||
log.Println("ERROR", "170050|读取网卡配置文件出错", err.Error()) | |||
return err | |||
} | |||
var sName, sRegs string | |||
var Reg *regexp.Regexp | |||
mNetCard := make(map[string]string, 0) | |||
for i, v := range mString { | |||
var err error | |||
if v == "" { | |||
err = errors.New("参数值为空") | |||
return err | |||
} | |||
switch i { | |||
case "Ip": | |||
mNetCard["address"] = v | |||
case "GateWay": | |||
mNetCard["gateway"] = v | |||
case "Dns": | |||
mNetCard["dns-nameserver"] = v | |||
case "NetMask": | |||
mNetCard["netmask"] = v | |||
} | |||
} | |||
for i, v := range mNetCard { | |||
sName = i | |||
sRegs = sName + "\\s+\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" | |||
Reg = regexp.MustCompile(sRegs) | |||
bOld := Reg.Find(bFile) | |||
bFile = bytes.Replace(bFile, bOld, []byte(i+" "+v), 1) | |||
} | |||
err = ioutil.WriteFile("/etc/network/interfaces", bFile, 644) | |||
if err != nil { | |||
panic(err) | |||
log.Println("ERROR", "170051|写入网卡配置文件出错", err.Error()) | |||
return err | |||
} | |||
return nil | |||
} |
@ -0,0 +1,21 @@ | |||
package helper | |||
import ( | |||
"strconv" | |||
"time" | |||
) | |||
func FormatDateTime(str string) string { | |||
date, err := strconv.ParseInt(str, 10, 64) | |||
if err != nil { | |||
return "" | |||
} | |||
return time.Unix(date, 0).Format("2006-01-02 15:04:05") | |||
} | |||
func FormatDate(str string) string { | |||
date, err := strconv.ParseInt(str, 10, 64) | |||
if err != nil { | |||
return "" | |||
} | |||
return time.Unix(date, 0).Format("2006-01-02") | |||
} |
@ -0,0 +1,17 @@ | |||
package helper | |||
import ( | |||
"testing" | |||
"time" | |||
) | |||
func Test_FormatDate(t *testing.T) { | |||
str := "1110" | |||
strconv := FormatDate(str) | |||
t.Log(strconv) | |||
timing := "2019/1/1 8:28" | |||
ret, err := time.ParseInLocation("2006/1/2 15:04", timing, time.Local) | |||
t.Log(ret.Unix()) | |||
t.Log(err) | |||
} |
@ -0,0 +1,71 @@ | |||
package helper | |||
import ( | |||
"crypto/rand" | |||
"encoding/hex" | |||
"fmt" | |||
) | |||
// Simple call | |||
func NewUUID() string { | |||
uuid, _ := GenerateUUID() | |||
return uuid | |||
} | |||
// GenerateRandomBytes is used to generate random bytes of given size. | |||
func GenerateRandomBytes(size int) ([]byte, error) { | |||
buf := make([]byte, size) | |||
if _, err := rand.Read(buf); err != nil { | |||
return nil, fmt.Errorf("failed to read random bytes: %v", err) | |||
} | |||
return buf, nil | |||
} | |||
const uuidLen = 16 | |||
// GenerateUUID is used to generate a random UUID | |||
func GenerateUUID() (string, error) { | |||
buf, err := GenerateRandomBytes(uuidLen) | |||
if err != nil { | |||
return "", err | |||
} | |||
return FormatUUID(buf) | |||
} | |||
func FormatUUID(buf []byte) (string, error) { | |||
if buflen := len(buf); buflen != uuidLen { | |||
return "", fmt.Errorf("wrong length byte slice (%d)", buflen) | |||
} | |||
return fmt.Sprintf("%x-%x-%x-%x-%x", | |||
buf[0:4], | |||
buf[4:6], | |||
buf[6:8], | |||
buf[8:10], | |||
buf[10:16]), nil | |||
} | |||
func ParseUUID(uuid string) ([]byte, error) { | |||
if len(uuid) != 2*uuidLen+4 { | |||
return nil, fmt.Errorf("uuid string is wrong length") | |||
} | |||
if uuid[8] != '-' || | |||
uuid[13] != '-' || | |||
uuid[18] != '-' || | |||
uuid[23] != '-' { | |||
return nil, fmt.Errorf("uuid is improperly formatted") | |||
} | |||
hexStr := uuid[0:8] + uuid[9:13] + uuid[14:18] + uuid[19:23] + uuid[24:36] | |||
ret, err := hex.DecodeString(hexStr) | |||
if err != nil { | |||
return nil, err | |||
} | |||
if len(ret) != uuidLen { | |||
return nil, fmt.Errorf("decoded hex is the wrong length") | |||
} | |||
return ret, nil | |||
} |
@ -0,0 +1,69 @@ | |||
package helper | |||
import ( | |||
"errors" | |||
"regexp" | |||
"strings" | |||
) | |||
/** | |||
* 验证 | |||
* 2020/08/10 | |||
*/ | |||
type Validate struct { | |||
Data []interface{} | |||
Title []string | |||
Rule []string //多个规则使用逗号(,)隔开 | |||
} | |||
func (v *Validate) Check() error { | |||
if len(v.Data) == 0 { | |||
return nil | |||
} | |||
if len(v.Data) != len(v.Title) || len(v.Data) != len(v.Rule) { | |||
return errors.New("验证参数不对应") | |||
} | |||
msg := make([]string, 0) | |||
var ok bool | |||
for key, data := range v.Data { | |||
rules := strings.Split(v.Rule[key], ",") //分隔所有规则 | |||
for _, rule := range rules { | |||
switch rule { | |||
case "require": | |||
ok = require(data) | |||
if !ok { | |||
msg = append(msg, StringJoin(v.Title[key], "不能为空")) | |||
} | |||
} | |||
} | |||
} | |||
if len(msg) == 0 { | |||
return nil | |||
} | |||
return errors.New(strings.Join(msg, ",")) | |||
} | |||
func require(data interface{}) bool { | |||
if ToString(data) == "" { | |||
return false | |||
} | |||
return true | |||
} | |||
// 判断手机号码 | |||
func IsMobile(mobile string) bool { | |||
result, _ := regexp.MatchString(`^(1[3|4|5|6|7|8]\d{9})$`, mobile) | |||
if result { | |||
return true | |||
} else { | |||
return false | |||
} | |||
} | |||
// 判断邮箱 | |||
func IsEmail(email string) bool { | |||
pattern := `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*` //匹配电子邮箱 | |||
reg := regexp.MustCompile(pattern) | |||
return reg.MatchString(email) | |||
} |
@ -0,0 +1,15 @@ | |||
package helper | |||
import ( | |||
"testing" | |||
) | |||
func Test_IsMobile(t *testing.T) { | |||
s := "1344456907s" | |||
ret := IsMobile(s) | |||
t.Log(ret) | |||
s = "+1@ee.22" | |||
ret = IsEmail(s) | |||
t.Log(ret) | |||
} |