123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260 |
- package utils
- import (
- "crypto/md5"
- "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
- }
|