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

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

// 去除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
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

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
89 90 91 92 93 94 95 96 97 98
}

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

// 缩短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
}
hujiebin's avatar
hujiebin committed
108 109 110 111 112 113 114 115 116

// 保留两位小数
func Decimal(value float64) float64 {
	newValue, err := strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
	if err != nil {
		return value
	}
	return newValue
}