github.com/15mga/kiwi@v0.0.2-0.20240324021231-b95d5c3ac751/sid/sid.go (about) 1 package sid 2 3 import ( 4 "encoding/hex" 5 "fmt" 6 7 "github.com/15mga/kiwi/util" 8 "github.com/bwmarrin/snowflake" 9 ) 10 11 const ( 12 Snowflake = "snowflake" 13 ) 14 15 var ( 16 _NameToFac = make(map[string]util.ToInt64) 17 ) 18 19 func BindIdFac(name string, to util.ToInt64) { 20 _NameToFac[name] = to 21 } 22 23 func GetIdWithName(name string) int64 { 24 fac, ok := _NameToFac[name] 25 if !ok { 26 panic("not exist " + name) 27 } 28 return fac() 29 } 30 31 func GetStrIdWithName(name string) string { 32 return hex.EncodeToString(util.Int64ToBytes(GetIdWithName(name))) 33 } 34 35 func SetNodeId(id int64) { 36 node, err := snowflake.NewNode(id) 37 if err != nil { 38 panic(fmt.Sprintf("generate node failed id:%d", id)) 39 } 40 BindIdFac(Snowflake, func() int64 { 41 return node.Generate().Int64() 42 }) 43 } 44 45 func GetId() int64 { 46 return GetIdWithName(Snowflake) 47 } 48 49 func GetStrId() string { 50 return hex.EncodeToString(util.Int64ToBytes(GetIdWithName(Snowflake))) 51 }