utils.go 1.91 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4
package utils

import (
	"encoding/json"
hujiebin's avatar
hujiebin committed
5
	"git.hilo.cn/hilo-common/resource/config"
hujiebin's avatar
hujiebin committed
6
	"git.hilo.cn/hilo-common/resource/mysql"
hujiebin's avatar
hujiebin committed
7
	"strings"
hujiebin's avatar
hujiebin committed
8
	"time"
hujiebin's avatar
hujiebin committed
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
)

// 去除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
}
hujiebin's avatar
hujiebin committed
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

func IfLogoutStr(condition bool, trueVal, falseVal string) string {
	if condition {
		return trueVal
	}
	return falseVal
}

func IfLogoutNick(condition bool, code string, nick string) string {
	if condition {
		return "Hilo No." + code
	}
	return nick
}

func IfLogout(logoutTime int64) bool {
	return logoutTime > 0 && time.Now().Unix() > logoutTime
}

func BirthdayToUint64(birthday *mysql.Timestamp) *uint64 {
	if *birthday == 0 {
		return nil
	}
	return (*uint64)(birthday)
}

//空字符串转成nil
func StrNil(msg string) *string {
	if msg == "" {
		return nil
	}
	return &msg
}

func TypeToUint8(t *mysql.Type) *uint8 {
	if *t == 0 {
		return nil
	} else {
		return (*uint8)(t)
	}
}

func StrToString(str *mysql.Str) *string {
	return (*string)(str)
}

func NumToUint32(num *mysql.Num) *uint32 {
	return (*uint32)(num)
hujiebin's avatar
hujiebin committed
87 88 89 90 91 92 93 94 95 96
}

func IsInStringList(str string, list []string) bool {
	for _, v := range list {
		if str == v {
			return true
		}
	}
	return false
}
hujiebin's avatar
hujiebin committed
97 98 99 100 101 102 103 104 105

// 缩短url: 去掉AWS前缀,以便aws接口使用
func StripAwsPrefix(url string) string {
	if !strings.HasPrefix(url, config.GetConfigAws().AWS_CDN) {
		return url
	}
	newUrl := url[len(config.GetConfigAws().AWS_CDN):]
	return newUrl
}