1 Star 0 Fork 0

天雨流芳 / go-micro-framework

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
idutil.go 2.11 KB
一键复制 编辑 原始数据 按行查看 历史
天雨流芳 提交于 2024-03-19 15:24 . 增加通用文件
package idutil
import (
"crypto/rand"
"gitee.com/tylf2018/go-micro-framework/pkg/common/util/iputil"
"gitee.com/tylf2018/go-micro-framework/pkg/common/util/stringutil"
"github.com/sony/sonyflake"
hashids "github.com/speps/go-hashids"
)
// Defiens alphabet.
const (
Alphabet62 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
Alphabet36 = "abcdefghijklmnopqrstuvwxyz1234567890"
)
var sf *sonyflake.Sonyflake
func init() {
var st sonyflake.Settings
st.MachineID = func() (uint16, error) {
ip := iputil.GetLocalIP()
return uint16([]byte(ip)[2])<<8 + uint16([]byte(ip)[3]), nil
}
sf = sonyflake.NewSonyflake(st)
}
// GetIntID returns uint64 uniq id.
func GetIntID() uint64 {
id, err := sf.NextID()
if err != nil {
panic(err)
}
return id
}
// GetInstanceID returns id format like: secret-2v69o5
func GetInstanceID(uid uint64, prefix string) string {
hd := hashids.NewData()
hd.Alphabet = Alphabet36
hd.MinLength = 6
hd.Salt = "x20k5x"
h := hashids.NewWithData(hd)
i, err := h.Encode([]int{int(uid)})
if err != nil {
panic(err)
}
return prefix + stringutil.Reverse(i)
}
// GetUUID36 returns id format like: 300m50zn91nwz5.
func GetUUID36(prefix string) string {
id := GetIntID()
hd := hashids.NewData()
hd.Alphabet = Alphabet36
h := hashids.NewWithData(hd)
i, err := h.Encode([]int{int(id)})
if err != nil {
panic(err)
}
return prefix + stringutil.Reverse(i)
}
func randString(letters string, n int) string {
output := make([]byte, n)
// We will take n bytes, one byte for each character of output.
randomness := make([]byte, n)
// read all random
_, err := rand.Read(randomness)
if err != nil {
panic(err)
}
l := len(letters)
// fill output
for pos := range output {
// get random item
random := randomness[pos]
// random % 64
randomPos := random % uint8(l)
// put into output
output[pos] = letters[randomPos]
}
return string(output)
}
// NewSecretID returns a secretID.
func NewSecretID() string {
return randString(Alphabet62, 36)
}
// NewSecretKey returns a secretKey or password.
func NewSecretKey() string {
return randString(Alphabet62, 32)
}
1
https://gitee.com/tylf2018/go-micro-framework.git
git@gitee.com:tylf2018/go-micro-framework.git
tylf2018
go-micro-framework
go-micro-framework
a23f37e8bd2b

搜索帮助

53164aa7 5694891 3bd8fe86 5694891