hashids

package module
v0.0.0-...-940cc3a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 9, 2020 License: MIT Imports: 2 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

https://github.com/speps/go-hashids 的方法封装,数字类型的 ID 转换为随机字符串 ID

不再维护该仓库,代码已迁移到 goutils

安装:

go get -u github.com/axiaoxin/hashids

用法示例example.go:

package main

import (
    "log"

    "github.com/axiaoxin/hashids"
)

func main() {
    salt := "my-salt:appid:region:uin"
    minLen := 8
    prefix := ""
    h, err := hashids.New(salt, minLen, prefix)
    if err != nil {
        log.Fatal(err)
    }
    var id int64 = 1
    strID, err := h.Encode(id)
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("int64 id %d encode to %s", id, strID)

    int64ID, err := h.Decode(strID)
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("string id %s decode to %d", strID, int64ID)
}

运行结果:

go run example.go
2020/02/26 13:28:11 int64 id 1 encode to 8Gnejq6A
2020/02/26 13:28:11 string id 8Gnejq6A decode to 1

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Hashids

type Hashids struct {
	HashID     *hashids.HashID
	HashIDData *hashids.HashIDData
	// contains filtered or unexported fields
}

Hashids 封装hashids方法

func New

func New(salt string, minLength int, prefix string) (*Hashids, error)

New 创建Hashids对象 salt可以使用用户创建记录时的用户唯一身份标识+当前时间戳的字符串作为值 minLength指定转换后的最小长度,随着数字ID的增大长度可能会变长

func (*Hashids) Decode

func (h *Hashids) Decode(hashID string) (int64, error)

Decode 将生成的随机字符串ID转为为原始的数字类型ID

func (*Hashids) Encode

func (h *Hashids) Encode(int64ID int64) (string, error)

Encode 将数字类型的ID转换为指定长度的随机字符串ID int64ID为需要转换的数字id,在没有自增主键ID时,可以采用当前用户已存在的记录数+1作为数字id,保证该数字在该用户下唯一

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址