package hashids import ( "git.ipao.vip/rogeecn/atom/container" "git.ipao.vip/rogeecn/atom/utils/opt" "github.com/speps/go-hashids/v2" ) func Provide(opts ...opt.Option) error { o := opt.New(opts...) var config Config if err := o.UnmarshalConfig(&config); err != nil { return err } return container.Container.Provide(func() (*Hasher, error) { data := hashids.NewData() data.MinLength = int(config.MinLength) if data.MinLength == 0 { data.MinLength = 10 } data.Salt = config.Salt if data.Salt == "" { data.Salt = "default-salt-key" } data.Alphabet = config.Alphabet if config.Alphabet == "" { data.Alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" } hasher, err := hashids.NewWithData(data) if err != nil { return nil, err } return &Hasher{ hasher: hasher, }, nil }, o.DiOptions()...) } type Hasher struct { hasher *hashids.HashID } func (h *Hasher) EncodeInt64(id ...int64) (string, error) { return h.hasher.EncodeInt64(id) } func (h *Hasher) MustEncodeInt64(id ...int64) string { s, err := h.hasher.EncodeInt64(id) if err != nil { panic(err) } return s } func (h *Hasher) DecodeInt64(hash string) ([]int64, error) { return h.hasher.DecodeInt64WithError(hash) } func (h *Hasher) DecodeOnlyInt64(hash string) (int64, error) { ints, err := h.hasher.DecodeInt64WithError(hash) if err != nil { return 0, err } if len(ints) == 0 { return 0, nil } return ints[0], nil } func (h *Hasher) MustDecodeInt64(hash string) []int64 { id, err := h.DecodeInt64(hash) if err != nil { panic(err) } return id } func (h *Hasher) MustDecodeOnlyInt64(hash string) int64 { id, err := h.DecodeInt64(hash) if err != nil { panic(err) } return id[0] }