使用Hashids隐藏自增ID

package main

import (
   "fmt"
   "github.com/speps/go-hashids"
)

const HashidsSalt = "www.manong.life" // 加盐
const HashidsMinlength = 16           // 哈希字符串最小长度

// IdToHash ID转哈希字符串
func IdToHash(id int) string {
   hashIDData := hashids.NewData()
   hashIDData.Salt = HashidsSalt
   hashIDData.MinLength = HashidsMinlength

   hashID, _ := hashids.NewWithData(hashIDData)
   hash, _ := hashID.Encode([]int{id})

   return hash
}

// HashToId 哈希字符串转ID
func HashToId(hash string) int {
   hashIDData := hashids.NewData()
   hashIDData.Salt = HashidsSalt
   hashIDData.MinLength = HashidsMinlength

   hashID, _ := hashids.NewWithData(hashIDData)
   id, _ := hashID.DecodeWithError(hash)

   return id[0]
}

func main() {
   //========== ID转哈希字符串 ==========//
   id := 1024
   hash := IdToHash(id)
   fmt.Printf("%+v => %+v \n", id, hash) // 1024 => 3aYQv8MdQNzgqGDB

   //========== 哈希字符串转ID ==========//
   id = HashToId(hash)
   fmt.Printf("%+v => %+v \n", hash, id) // 3aYQv8MdQNzgqGDB => 1024
}

Copyright © 2024 码农人生. All Rights Reserved