package util
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
i18n "github.com/suisrc/gin-i18n"
"io"
"log"
"math/rand"
"net/http"
"os"
"path"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
)
func Log(data string, strs ...string) {
var filename = "./log/test.log"
var pre = "[江湖故人]"
if len(strs) > 0 {
filename = "./log/" + strs[0] + ".log"
}
if len(strs) > 1 {
pre = "[" + strs[1] + "]"
}
// fmt.Println(filename,pre)
logFile, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
fmt.Println("open log file failed, err:", err)
return
}
defer logFile.Close()
log.SetOutput(logFile)
log.SetFlags(log.Llongfile | log.Lmicroseconds | log.Ldate)
log.SetPrefix(pre)
log.Println(data)
}
func Try(userFn func(), catchFn func(err interface{})) {
defer func() {
if err := recover(); any(err) != nil {
catchFn(err)
}
}()
userFn()
}
func StructToMap(obj interface{}) map[string]interface{} {
t := reflect.TypeOf(obj)
v := reflect.ValueOf(obj)
var data = make(map[string]interface{})
for i := 0; i < t.NumField(); i++ {
data[t.Field(i).Name] = v.Field(i).Interface()
}
return data
}
func StructToMapJson(obj interface{}) map[string]interface{} {
t := reflect.TypeOf(obj)
v := reflect.ValueOf(obj)
var data = make(map[string]interface{})
for i := 0; i < t.NumField(); i++ {
jsonKey := t.Field(i).Tag.Get("json")
if jsonKey != "-" {
data[jsonKey] = v.Field(i).Interface()
}
}
return data
}
func Trans(c *gin.Context, key string) (rekey string) {
rekey = i18n.FormatText(c, &i18n.Message{ID: key})
return
}
//输入文件路径,根据返回的bool值来判断文件或文件夹是否存在
func IsFileExist(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
// 获取文件的md5码
func getFileMd5(filename string) string {
// 文件全路径名
path := fmt.Sprintf("./%s", filename)
pFile, err := os.Open(path)
if err != nil {
fmt.Errorf("打开文件失败,filename=%v, err=%v", filename, err)
return ""
}
defer pFile.Close()
md5h := md5.New()
io.Copy(md5h, pFile)
return hex.EncodeToString(md5h.Sum(nil))
}
func UploadImg(c *gin.Context) (backpath string, errmsg string) {
f, err := c.FormFile("imgfile")
errmsg = "ok"
var filepath = ""
if err != nil {
//errmsg = "上传失败!"
errmsg = err.Error()
return
} else {
fileExt := strings.ToLower(path.Ext(f.Filename))
if fileExt != ".png" && fileExt != ".jpg" && fileExt != ".gif" && fileExt != ".jpeg" {
errmsg = "上传失败!只允许png,jpg,gif,jpeg文件"
return
}
fileName := ShortMd5(fmt.Sprintf("%s%s", f.Filename, time.Now().String()))
fpath := "/public/"
if gin.Mode() == gin.ReleaseMode {
fpath = "/www/wwwroot/server.wivs.shop/public/go_img/"
}
fildDir := fmt.Sprintf("%s%s/", fpath, time.Now().Format("2006-01-02"))
isExist, _ := IsFileExist(fildDir)
if !isExist {
os.MkdirAll(fildDir, 0777)
//os.Mkdir(fildDir,os.ModePerm)
}
filepath = fmt.Sprintf("%s%s%s", fildDir, fileName, fileExt)
c.SaveUploadedFile(f, filepath)
backpath = strings.ReplaceAll(filepath, "/www/wwwroot/server.wivs.shop/public", "")
return
}
}
func GrUpload(c *gin.Context, savepath string) (backpath string, errmsg string) {
f, err := c.FormFile("imgfile")
errmsg = "ok"
var filepath = ""
if err != nil {
//errmsg = "上传失败!"
errmsg = err.Error()
return
} else {
fileExt := strings.ToLower(path.Ext(f.Filename))
if fileExt != ".png" && fileExt != ".jpg" && fileExt != ".gif" && fileExt != ".jpeg" {
errmsg = "上传失败!只允许png,jpg,gif,jpeg文件"
return
}
fileName := ShortMd5(fmt.Sprintf("%s%s", f.Filename, time.Now().String()))
fpath := "/public/" + savepath + `/`
if gin.Mode() == gin.ReleaseMode {
fpath = `/www/wwwroot/server.wivs.shop/public/go_img/` + savepath + `/`
}
fildDir := fmt.Sprintf("%s%s/", fpath, time.Now().Format("2006-01-02"))
isExist, _ := IsFileExist(fildDir)
if !isExist {
os.MkdirAll(fildDir, 0777)
//os.Mkdir(fildDir,os.ModePerm)
}
filepath = fmt.Sprintf("%s%s%s", fildDir, fileName, fileExt)
c.SaveUploadedFile(f, filepath)
backpath = strings.ReplaceAll(filepath, `/www/wwwroot/server.wivs.shop/public`, ``)
return
}
}
func ShortMd5(s string) string {
m := md5.New()
m.Write([]byte(s))
str := hex.EncodeToString(m.Sum(nil))
return string([]byte(str)[16:])
}
func Md5(s string) string {
m := md5.New()
m.Write([]byte(s))
return hex.EncodeToString(m.Sum(nil))
}
func VerifyEmailFormat(email string) bool {
//pattern := `\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*` //
pattern := `^[0-9a-z][_.0-9a-z-]{0,31}@([0-9a-z][0-9a-z-]{0,30}[0-9a-z]\.){1,4}[a-z]{2,4}$`
reg := regexp.MustCompile(pattern)
return reg.MatchString(email)
}
//mobile verify
func VerifyMobileFormat(mobileNum string) bool {
regular := "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$"
reg := regexp.MustCompile(regular)
return reg.MatchString(mobileNum)
}
func Forbacks(c *gin.Context, ori []map[string]interface{}, args ...string) {
var msg string
if args != nil {
msg = args[0]
} else {
msg = "success"
}
c.JSON(http.StatusOK, gin.H{
"code": 1,
"msg": msg,
"data": ori,
})
}
func Forback(c *gin.Context, ori map[string]interface{}) {
val, ok := ori["msg"]
var msg string
if ok {
msg = Strval(val)
delete(ori, "msg")
} else {
msg = "success"
}
c.JSON(http.StatusOK, gin.H{
"code": 1,
"msg": msg,
"data": ori,
})
}
func Errback(c *gin.Context, msg string) {
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": msg,
})
}
func Back(c *gin.Context, data map[string]interface{}) {
c.JSON(http.StatusOK, data)
}
func Numeric(val interface{}) int {
rs, err := strconv.Atoi(Strval(val))
if err != nil {
return -1
} else {
return rs
}
}
func Float(val interface{}) float64 {
rs, err := strconv.ParseFloat(Strval(val), 64)
if err != nil {
return 0.00
} else {
return rs
}
}
func InArray(needle interface{}, hystack interface{}) bool {
switch key := needle.(type) {
case string:
for _, item := range hystack.([]string) {
if key == item {
return true
}
}
case int:
for _, item := range hystack.([]int) {
if key == item {
return true
}
}
case int64:
for _, item := range hystack.([]int64) {
if key == item {
return true
}
}
default:
return false
}
return false
}
func Md5Encrypt(s string) string {
//2022gr
m := md5.New()
m.Write([]byte(s))
m.Write([]byte(string("2022gr")))
return hex.EncodeToString(m.Sum(nil))
}
func MbStrLen(str string) int {
return utf8.RuneCountInString(str)
}
func GetRandom(length int) string {
if length < 1 {
return ""
}
//char := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
char := "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
<-time.After(time.Nanosecond)
charArr := strings.Split(char, "")
charlen := len(charArr)
ran := rand.New(rand.NewSource(time.Now().UnixNano()))
rchar := make([]string, 0, length)
for i := 1; i <= length; i++ {
rchar = append(rchar, charArr[ran.Intn(charlen)])
}
return strings.Join(rchar, "")
}
func GetNumRandom(length int) string {
if length < 1 {
return ""
}
//char := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
char := "0123456789"
<-time.After(time.Nanosecond)
charArr := strings.Split(char, "")
charlen := len(charArr)
ran := rand.New(rand.NewSource(time.Now().UnixNano()))
rchar := make([]string, 0, length)
for i := 1; i <= length; i++ {
rchar = append(rchar, charArr[ran.Intn(charlen)])
}
return strings.Join(rchar, "")
}
func Parseval(value interface{}) string {
rs, ok := value.(string)
if ok {
return rs
}
var data = make(map[string]interface{})
data, ok = value.(map[string]interface{})
if ok {
s1 := make([]string, len(data))
x := 0
for k, v := range data {
s1[x] = "`" + k + "`" + " = " + "\"" + Strval(v) + "\""
x++
}
wstr := strings.Join(s1, " and ")
return wstr
} else {
return ""
}
}
func isMap(x interface{}) bool {
t := fmt.Sprintf("%T", x)
return strings.HasPrefix(t, "map[")
}
func Strval(value interface{}) string {
var key string
if value == nil {
return key
}
switch value.(type) {
case float64:
ft := value.(float64)
key = strconv.FormatFloat(ft, 'f', -1, 64)
case float32:
ft := value.(float32)
key = strconv.FormatFloat(float64(ft), 'f', -1, 64)
case int:
it := value.(int)
key = strconv.Itoa(it)
case uint:
it := value.(uint)
key = strconv.Itoa(int(it))
case int8:
it := value.(int8)
key = strconv.Itoa(int(it))
case uint8:
it := value.(uint8)
key = strconv.Itoa(int(it))
case int16:
it := value.(int16)
key = strconv.Itoa(int(it))
case uint16:
it := value.(uint16)
key = strconv.Itoa(int(it))
case int32:
it := value.(int32)
key = strconv.Itoa(int(it))
case uint32:
it := value.(uint32)
key = strconv.Itoa(int(it))
case int64:
it := value.(int64)
key = strconv.FormatInt(it, 10)
case uint64:
it := value.(uint64)
key = strconv.FormatUint(it, 10)
case string:
key = value.(string)
case []byte:
key = string(value.([]byte))
default:
newValue, _ := json.Marshal(value)
key = string(newValue)
}
return key
}