util.go 2.36 KB
Newer Older
chenweijian's avatar
chenweijian committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
package _const

import (
	"encoding/json"
	"fmt"
	"hilo-user/mylogrus"
	"hilo-user/resource/config"
	"net"
	"runtime/debug"
	"strings"
	"time"
)

const DEFAULT_LANG = "en"
const DATETIME_FORMAT = "2006-01-02 15:04:05"
const DATE_FORMAT = "2006-01-02"
const DefaultAvatarMan = "hilo/manager/ea48b62d54a24a709de3c38702c89995.png"

func GetZeroTime(t time.Time) time.Time {
	return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}

// 取最近的一个星期n
func GetLastDayOfWeek(t time.Time, n time.Weekday) time.Time {
	weekDay := t.Weekday()
	// 校正日期
	if weekDay < n {
		weekDay = 7 - n + weekDay
	} else {
		weekDay = weekDay - n
	}
	return t.AddDate(0, 0, -(int(weekDay)))
}

// 补全url,区分处理oss和aws两种情况
func MakeFullUrl(url string) string {
	if strings.HasPrefix(url, config.GetConfigOss().OSS_CDN) || strings.HasPrefix(url, config.GetConfigAws().AWS_CDN) {
		return url
	} else if strings.HasPrefix(url, "nextvideo/") {
		return config.GetConfigOss().OSS_CDN + url
	} else if strings.HasPrefix(url, config.GetConfigAws().AWS_DIR) {
		return config.GetConfigAws().AWS_CDN + url
	} else {
		return url
	}
}

// 去除slice中的重复元素
func UniqueSliceUInt64(sliceIn []uint64) []uint64 {
	sliceOut := make([]uint64, 0, len(sliceIn))
	m := make(map[uint64]struct{}, len(sliceIn))
	for _, i := range sliceIn {
		if _, ok := m[i]; !ok {
			m[i] = struct{}{}
			sliceOut = append(sliceOut, i)
		}
	}
	return sliceOut
}

func ToString(s interface{}) (string, error) {
	b, err := json.Marshal(s)
	if err != nil {
		return "", nil
	}
	return string(b), nil
}

func SliceToMapUInt64(s []uint64) map[uint64]struct{} {
	m := make(map[uint64]struct{}, len(s))
	for _, i := range s {
		m[i] = struct{}{}
	}
	return m
}

func GetClientIp() (string, error) {
	addrs, err := net.InterfaceAddrs()

	if err != nil {
		return "", err
	}

	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipNet, ok := address.(*net.IPNet); ok && ipNet.IP.IsGlobalUnicast() {
			//if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
			if ipNet.IP.To4() != nil {
				return ipNet.IP.String(), nil
			}

		}
	}
	return "", fmt.Errorf("can not find the client ip address")
}

func CheckGoPanic() {
	if r := recover(); r != nil {
		//打印错误堆栈信息
		mylogrus.MyLog.Errorf("ACTION PANIC: %v, stack: %v", r, string(debug.Stack()))
	}
}