gocron/modules/utils/utils.go

108 lines
2.1 KiB
Go
Raw Normal View History

2017-03-10 09:08:51 +00:00
package utils
import (
2017-09-16 09:58:33 +00:00
"crypto/md5"
"encoding/hex"
"fmt"
"github.com/Tang-RoseChild/mahonia"
"math/rand"
"os"
"runtime"
"strings"
"time"
2017-03-10 09:08:51 +00:00
)
// 生成长度为length的随机字符串
func RandString(length int64) string {
2017-09-16 09:58:33 +00:00
sources := []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
result := []byte{}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
sourceLength := len(sources)
var i int64 = 0
for ; i < length; i++ {
result = append(result, sources[r.Intn(sourceLength)])
}
return string(result)
2017-03-10 09:08:51 +00:00
}
// 生成32位MD5摘要
func Md5(str string) string {
2017-09-16 09:58:33 +00:00
m := md5.New()
m.Write([]byte(str))
2017-03-10 09:08:51 +00:00
2017-09-16 09:58:33 +00:00
return hex.EncodeToString(m.Sum(nil))
2017-03-10 09:08:51 +00:00
}
// 生成0-max之间随机数
func RandNumber(max int) int {
2017-09-16 09:58:33 +00:00
r := rand.New(rand.NewSource(time.Now().UnixNano()))
2017-03-10 09:08:51 +00:00
2017-09-16 09:58:33 +00:00
return r.Intn(max)
}
// 判断当前系统是否是windows
func IsWindows() bool {
2017-09-16 09:58:33 +00:00
return runtime.GOOS == "windows"
}
// GBK编码转换为UTF8
func GBK2UTF8(s string) (string, bool) {
2017-09-16 09:58:33 +00:00
dec := mahonia.NewDecoder("gbk")
2017-09-16 09:58:33 +00:00
return dec.ConvertStringOK(s)
2017-04-28 03:54:46 +00:00
}
2017-04-28 06:55:24 +00:00
// 批量替换字符串
2017-09-16 09:58:33 +00:00
func ReplaceStrings(s string, old []string, replace []string) string {
if s == "" {
return s
}
if len(old) != len(replace) {
return s
}
for i, v := range old {
s = strings.Replace(s, v, replace[i], 1000)
}
return s
2017-04-28 06:55:24 +00:00
}
2017-04-30 17:12:07 +00:00
func InStringSlice(slice []string, element string) bool {
2017-09-16 09:58:33 +00:00
element = strings.TrimSpace(element)
for _, v := range slice {
if strings.TrimSpace(v) == element {
return true
}
}
return false
2017-04-30 17:12:07 +00:00
}
2017-04-28 03:54:46 +00:00
// 转义json特殊字符
2017-09-16 09:58:33 +00:00
func EscapeJson(s string) string {
specialChars := []string{"\\", "\b", "\f", "\n", "\r", "\t", "\""}
replaceChars := []string{"\\\\", "\\b", "\\f", "\\n", "\\r", "\\t", "\\\""}
2017-04-28 03:54:46 +00:00
2017-09-16 09:58:33 +00:00
return ReplaceStrings(s, specialChars, replaceChars)
2017-05-01 05:59:52 +00:00
}
// 判断文件是否存在及是否有权限访问
2017-05-01 05:59:52 +00:00
func FileExist(file string) bool {
2017-09-16 09:58:33 +00:00
_, err := os.Stat(file)
if os.IsNotExist(err) {
return false
}
if os.IsPermission(err) {
return false
}
return true
}
// 格式化环境变量
func FormatUnixEnv(key, value string) string {
2017-09-16 09:58:33 +00:00
return fmt.Sprintf("export %s=%s; ", key, value)
}