package utils import ( "crypto/md5" "crypto/sha1" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "math/rand" "net" "os" "reflect" "regexp" "strconv" "strings" "time" "unicode" ) var ( DB_QUERY_WHERE_EMPTY = errors.New("where is empty") DB_RECORD_NOT_EXISTS = errors.New("record is not exists") DB_DUPLICATE = errors.New("database duplicate") ) func GetUniqueLogID(cmd string) string { return fmt.Sprintf("%d_%s", time.Now().Unix(), cmd) } // 获取偏移天数的某天的某个时刻的时间戳 func GetTimestampInOffsetDay(offsetDay, hour, min, sec int) int64 { nowTime := time.Now() todayZeroTime := time.Date(nowTime.Year(), nowTime.Month(), nowTime.Day(), 0, 0, 0, 0, time.Local) offsetDayZeroTime := todayZeroTime.AddDate(0, 0, offsetDay) return offsetDayZeroTime.Unix() + int64(hour*3600+min*60+sec) } func BeToday(ts int64) bool { theTime := time.Unix(ts, 0) nowTime := time.Now() // 年、月、日都相同,则是同一天 return (theTime.Year() == nowTime.Year() && theTime.Month() == nowTime.Month() && theTime.Day() == nowTime.Day()) } // 获取某个时间戳的0点时间戳、24点时间戳、日期 func Get0_24TimestampAndDate(ts int64) (ts0, ts24 int64, date string) { theTime := time.Unix(ts, 0) theZeroTime := time.Date(theTime.Year(), theTime.Month(), theTime.Day(), 0, 0, 0, 0, time.Local) ts0 = theZeroTime.Unix() // 0点时间戳 ts24 = theZeroTime.AddDate(0, 0, 1).Unix() // 24点时间戳 date = theZeroTime.Format("2006-01-02") // 日期 return } // 获取args对应的json字符串 func MarshalJsonString(args ...interface{}) (result string) { if len(args) > 0 { if r, err := json.Marshal(args); err == nil { result = string(r) } } return } func GetStructNotZeroField(arg interface{}) []string { v := reflect.ValueOf(arg) if v.Kind() == reflect.Ptr { v = v.Elem() } result := make([]string, 0) if v.Kind() == reflect.Struct { numField := v.NumField() for i := 0; i < numField; i++ { if !reflect.DeepEqual(v.Field(i).Interface(), reflect.Zero(v.Field(i).Type()).Interface()) { result = append(result, v.Type().Field(i).Name) } } } return result } // 生成订单号 func GenOrderNO(orderType int) string { nowTime := time.Now() nowDate := nowTime.Format("20060102") ym := string([]byte(nowDate)[3:6]) d := string([]byte(nowDate)[6:]) r := rand.New(rand.NewSource(time.Now().UnixNano())) return fmt.Sprintf("%d%s%d%s%05d", orderType, ym, r.Intn(10), d, r.Intn(10000)) } func GetRuneSubstring(src string, start, length int) string { rs := []rune(src) rl := len(rs) end := 0 if start < 0 { start = rl - 1 + start } end = start + length if start > end { start, end = end, start } if start < 0 { start = 0 } if start > rl { start = rl } if end < 0 { end = 0 } if end > rl { end = rl } return string(rs[start:end]) } func MD5(text string) string { h := md5.New() h.Write([]byte(text)) return hex.EncodeToString(h.Sum(nil)) } func SHA256(text string) string { h := sha256.New() h.Write([]byte(text)) return hex.EncodeToString(h.Sum(nil)) } func GetEnv(name string) string { value := os.Getenv(name) if value == "" { fmt.Printf(`hasn't %s env var\n`, name) os.Exit(1) } return value } func Base64URLDecode(data string) ([]byte, error) { var missing = (4 - len(data)%4) % 4 data += strings.Repeat("=", missing) return base64.URLEncoding.DecodeString(data) } func Base64UrlSafeEncode(source []byte) string { // Base64 Url Safe is the same as Base64 but does not contain '/' and '+' (replaced by '_' and '-') and trailing '=' are removed. bytearr := base64.StdEncoding.EncodeToString(source) safeurl := strings.Replace(string(bytearr), "/", "_", -1) safeurl = strings.Replace(safeurl, "+", "-", -1) safeurl = strings.Replace(safeurl, "=", "", -1) return safeurl } //生成reportId 唯一标识 func GenReportID(module string) string { macAddr := "" for _, addr := range macAddrs() { macAddr += addr } if macAddr == "" { macAddr = RandomString(10) } reportId := macAddr + module + strconv.FormatInt(time.Now().UnixNano(), 10) return MD5(reportId) } func macAddrs() (macAddrs []string) { netInterfaces, err := net.Interfaces() if err != nil { return macAddrs } for _, netInterface := range netInterfaces { macAddr := netInterface.HardwareAddr.String() if len(macAddr) == 0 { continue } macAddrs = append(macAddrs, macAddr) } return macAddrs } //根据length获取随机字符串 func RandomString(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 ParsePlate(plate string) (string, string) { var index int for i, r := range plate { if !unicode.Is(unicode.Scripts["Han"], r) { index = i break } } sf := plate[0:index] hphm := plate[index:] return sf, hphm } func MobileVerify(number string) bool { regular := `^1([38][0-9]|14[57]|5[^4])\d{8}$` reg := regexp.MustCompile(regular) return reg.MatchString(number) } func CheckPlate(plate string, plateType string) (string, error) { var index int plate = strings.Replace(plate, " ", "", -1) for i, r := range plate { if !unicode.Is(unicode.Scripts["Han"], r) { index = i break } } if index != 3 { return "", errors.New("车牌格式错误") } if len(plate[index:]) != 6 && len(plate[index:]) != 7 { return "", errors.New("车牌格式错误") } if len((plate[index:])) == 7 { if plateType != "51" && plateType != "52" && plateType != "" { return "", errors.New("车牌格式错误") } } return plate, nil } func CheckVin(vin string) (string, error) { vin = strings.Replace(vin, " ", "", -1) if len(vin) != 17 { return "", errors.New("vin码格式错误") } return vin, nil } // 判断是否在字符串数组中 func InStrArr(arr []string, verify string) bool { for _, v := range arr { if v == verify { return true } } return false } func LimiterEnCode(s string) string { h := sha1.New() h.Write([]byte(s)) return hex.EncodeToString(h.Sum(nil))[:8] }