random

package
v0.19.4 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-08-05 10:50:01 * @FilePath: \go-toolbox\pkg\random\business.go * @Description: 生成业务相关的随机数据 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2026-01-05 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-01-05 15:16:27 * @FilePath: \go-toolbox\pkg\random\domain.go * @Description: 域名相关随机生成工具 * * Copyright (c) 2026 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2026-01-28 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-01-28 00:00:00 * @FilePath: \go-toolbox\pkg\random\duration.go * @Description: 随机时间相关工具函数 * * Copyright (c) 2026 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-12-12 23:03:57 * @FilePath: \go-toolbox\pkg\random\generate.go * @Description: 随机数据生成器 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-13 18:15:29 * @FilePath: \go-toolbox\pkg\random\model.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-08 03:59:11 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-12-12 23:05:08 * @FilePath: \go-toolbox\pkg\random\rand.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-06-17 13:15:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-06-17 13:55:17 * @FilePath: \go-toolbox\pkg\random\surnames.go * @Description: * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

Index

Constants

View Source
const (
	// 自定义数字区间
	DEC_BYTES = "0123456789"
	// 自定义hex区间
	HEX_BYTES = "ABCDEF0123456789"
	// 自定义字符区间
	ALPHA_BYTES  = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
	LETTER_BYTES = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

	LETTER_IDX_BITS = 6                      // 6 bits to represent a letter index
	LETTER_IDX_MASK = 1<<LETTER_IDX_BITS - 1 // All 1-bits, as many as letterIdxBits
	LETTER_IDX_MAX  = 31 / LETTER_IDX_BITS   // # of letter indices fitting in 31 bits
)

Variables

View Source
var SurnameData = []SurnameInfo{}/* 481 elements not displayed */

Functions

func ClearAllGenerators

func ClearAllGenerators()

ClearAllGenerators 清除所有已注册的生成器

func FRandAlphaBytes

func FRandAlphaBytes(n int) []byte

FRandAlphaBytes generates random alpha bytes.

func FRandAlphaString

func FRandAlphaString(n int) string

FRandAlphaString 指定长度的随机字母字符串

func FRandBool

func FRandBool() bool

生成随机布尔值

func FRandBytes

func FRandBytes(n int) []byte

FRandBytes random bytes, but faster.

func FRandBytesJSON

func FRandBytesJSON(length int) (string, error)

FRandBytesJSON 生成指定长度的随机字节字符串,并返回 JSON 格式

func FRandBytesLetters

func FRandBytesLetters(n int, letters string) []byte

FRandBytesLetters 生成指定长度的字符切片

func FRandDecBytes

func FRandDecBytes(n int) []byte

RandDecBytes 指定长度的随机数字切片

func FRandDecString

func FRandDecString(n int) string

FRandDecString 指定长度的随机数字字符串

func FRandHexBytes

func FRandHexBytes(n int) []byte

FRandHexBytes generates random hexadecimal bytes.

func FRandHexString

func FRandHexString(n int) string

FRandHexString 指定长度的随机 hex 字符串

func FRandInt

func FRandInt(min, max int) int

FRandInt (>=)min - (<)max

func FRandString

func FRandString(n int) string

FRandString a random string, which may contain uppercase letters, lowercase letters and numbers. Ref: stackoverflow.icza

func FRandTime

func FRandTime() time.Time

生成随机时间

func FRandUint32

func FRandUint32(min, max uint32) uint32

FRandUint32 (>=)min - (<)max

func FastIntn

func FastIntn(n int) int

FastIntn this is similar to rand.Intn, but faster. A non-negative pseudo-random number in the half-open interval [0,n). Return 0 if n <= 0.

func FastRand

func FastRand() uint32

FastRand 随机数

func FastRand64

func FastRand64() uint64

func FastRandn

func FastRandn(n uint32) uint32

FastRandn 等同于 FastRandn() % n, 但更快 See https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/

func FastRandu

func FastRandu() uint

func GenerateAvailablePort

func GenerateAvailablePort(ports ...int) (int, error)

GenerateAvailablePort 返回一个随机的可用端口号 如果未提供ports参数或提供的参数长度不为2,则使用默认端口范围1024到65535

func GenerateRandModel

func GenerateRandModel(model interface{}, opts ...*GenerateRandModelOptions) (interface{}, string, error)

GenerateRandModel 生成随机模型的 JSON 格式

func JoinDomainsWithTLDs

func JoinDomainsWithTLDs(domains []string, tlds []string, priorityTLDs ...string) []string

JoinDomainsWithTLDs 将域名关键词与多个TLD(顶级域名)拼接 参数:

  • domains: 域名关键词列表(不包含后缀)
  • tlds: TLD列表,如 ["com", "net", "org"]
  • priorityTLDs: 优先级TLD列表(可选),指定哪些TLD应该排在前面,默认为 ["com"]

返回:

  • []string: 拼接后的完整域名列表(按优先级TLD、其他TLD字母顺序分组)

示例:

  • JoinDomainsWithTLDs([]string{"game", "shop"}, []string{"com", "net", "org"}) -> ["game.com", "shop.com", "game.net", "shop.net", "game.org", "shop.org"]
  • JoinDomainsWithTLDs([]string{"game", "shop"}, []string{"com", "net", "org"}, "net", "com") -> ["game.net", "shop.net", "game.com", "shop.com", "game.org", "shop.org"]

func ListRegisteredGenerators

func ListRegisteredGenerators() []string

ListRegisteredGenerators 列出所有已注册的生成器

func NewRand

func NewRand(seed ...int64) *rand.Rand

NewRand goroutine-safe rand.Rand, optional seed value

func RandBusinessHour

func RandBusinessHour() time.Time

RandBusinessHour 生成工作时间内的随机时间点(9:00-18:00) 返回:

  • time.Time: 今天工作时间内的随机时间点

示例:

randTime := random.RandBusinessHour()
fmt.Println(randTime.Format("15:04:05")) // 输出: 09:00:00 到 18:00:00 之间的时间

func RandDate

func RandDate(startDate, endDate time.Time) time.Time

RandDate 生成指定日期范围内的随机日期(时间部分为 00:00:00) 参数:

  • startDate: 开始日期
  • endDate: 结束日期

返回:

  • time.Time: 随机生成的日期

示例:

// 生成2024年内的随机日期
start := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
end := time.Date(2024, 12, 31, 0, 0, 0, 0, time.UTC)
randDate := random.RandDate(start, end)

func RandDuration

func RandDuration(min, max time.Duration) time.Duration

RandDuration 生成指定范围内的随机时间间隔 参数:

  • min: 最小时间间隔
  • max: 最大时间间隔

返回:

  • time.Duration: 随机生成的时间间隔,范围在 [min, max) 之间

示例:

// 生成 100ms 到 500ms 之间的随机延迟
delay := random.RandDuration(100*time.Millisecond, 500*time.Millisecond)

// 生成 1s 到 5s 之间的随机延迟
delay := random.RandDuration(1*time.Second, 5*time.Second)

func RandFloat

func RandFloat(min, max float64) (v float64)

RandFloat *

  • @Description: 随机小数
  • @param min
  • @param max
  • @return v

func RandHex

func RandHex(bytesLen int, customBytes ...string) string

RandHex 随机一个hex字符串

func RandHour

func RandHour() int

RandHour 生成随机的小时数(0-23) 返回:

  • int: 随机的小时数

示例:

hour := random.RandHour()
fmt.Println(hour) // 输出: 0-23 之间的数字

func RandInt

func RandInt(min, max int) (v int)

RandInt *

  • @Description: 随机整数
  • @param start
  • @param end
  • @return v

func RandMinute

func RandMinute() int

RandMinute 生成随机的分钟数(0-59) 返回:

  • int: 随机的分钟数

示例:

minute := random.RandMinute()
fmt.Println(minute) // 输出: 0-59 之间的数字

func RandMonth

func RandMonth() time.Month

RandMonth 生成随机的月份 返回:

  • time.Month: 随机的月份(1=January, 2=February, ..., 12=December)

示例:

month := random.RandMonth()
fmt.Println(month) // 输出: January, February, 等等

func RandNumber

func RandNumber(length int, customBytes ...string) string

RandNumber 随机一个数字字符串

func RandNumerical

func RandNumerical[T types.Numerical](start, end T, step ...T) []T

RandNumerical 泛型函数,生成从 start 到 end(包含)的切片

func RandNumericalLargeSlice

func RandNumericalLargeSlice[T types.Numerical](largeSize ...int) []T

RandNumericalLargeSlice 随机生成大数据整数切片

func RandNumericalWithRandomStep

func RandNumericalWithRandomStep[T types.Numerical](start, end, minStep, maxStep T) []T

RandNumericalWithRandomStep 泛型函数,生成从 start 到 end(包含或不超过) 每一步随机步长在 [minStep, maxStep] 范围内(浮点数或整数)

func RandSecond

func RandSecond() int

RandSecond 生成随机的秒数(0-59) 返回:

  • int: 随机的秒数

示例:

second := random.RandSecond()
fmt.Println(second) // 输出: 0-59 之间的数字

func RandString

func RandString(n int, mode RandType) string

RandString *

  • @Description: 随机生成字符串
  • @param n 字符串长度
  • @param mode 字符串模式 random.NUMBER|random.LOWERCASE|random.SPECIAL|random.CAPITAL)
  • @return str 生成的字符串

func RandStringSlice

func RandStringSlice(count, len int, mode RandType) (result []string)

RandStringSlice 指定长度的随机字符串

func RandTimeBetween

func RandTimeBetween(start, end time.Time) time.Time

RandTimeBetween 生成指定时间范围内的随机时间点 参数:

  • start: 开始时间
  • end: 结束时间

返回:

  • time.Time: 随机生成的时间点,范围在 [start, end) 之间

示例:

// 生成今天 00:00 到现在之间的随机时间
today := time.Now().Truncate(24 * time.Hour)
randTime := random.RandTimeBetween(today, time.Now())

// 生成过去7天内的随机时间
weekAgo := time.Now().Add(-7 * 24 * time.Hour)
randTime := random.RandTimeBetween(weekAgo, time.Now())

func RandTimeInFuture

func RandTimeInFuture(duration time.Duration) time.Time

RandTimeInFuture 生成未来指定时间范围内的随机时间点 参数:

  • duration: 未来的时间范围

返回:

  • time.Time: 随机生成的未来时间点

示例:

// 生成未来24小时内的随机时间
randTime := random.RandTimeInFuture(24 * time.Hour)

// 生成未来7天内的随机时间
randTime := random.RandTimeInFuture(7 * 24 * time.Hour)

func RandTimeInPast

func RandTimeInPast(duration time.Duration) time.Time

RandTimeInPast 生成过去指定时间范围内的随机时间点 参数:

  • duration: 过去的时间范围

返回:

  • time.Time: 随机生成的过去时间点

示例:

// 生成过去24小时内的随机时间
randTime := random.RandTimeInPast(24 * time.Hour)

// 生成过去30天内的随机时间
randTime := random.RandTimeInPast(30 * 24 * time.Hour)

func RandTimeOfDay

func RandTimeOfDay() time.Time

RandTimeOfDay 生成当天的随机时间点 返回:

  • time.Time: 今天的随机时间点

示例:

randTime := random.RandTimeOfDay()
fmt.Println(randTime.Format("15:04:05")) // 输出: 今天的某个时间,如 14:23:45

func RandUnixTimestamp

func RandUnixTimestamp(minTimestamp, maxTimestamp int64) int64

RandUnixTimestamp 生成指定范围内的随机 Unix 时间戳(秒) 参数:

  • minTimestamp: 最小时间戳
  • maxTimestamp: 最大时间戳

返回:

  • int64: 随机的 Unix 时间戳

示例:

// 生成2024年内的随机时间戳
start := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC).Unix()
end := time.Date(2024, 12, 31, 23, 59, 59, 0, time.UTC).Unix()
timestamp := random.RandUnixTimestamp(start, end)

func RandWeekday

func RandWeekday() time.Weekday

RandWeekday 生成随机的星期几 返回:

  • time.Weekday: 随机的星期(0=Sunday, 1=Monday, ..., 6=Saturday)

示例:

weekday := random.RandWeekday()
fmt.Println(weekday) // 输出: Monday, Tuesday, 等等

func RandomCompany

func RandomCompany() string

RandomCompany 生成随机公司名称

func RandomEmail

func RandomEmail() string

RandomEmail 生成随机邮箱

func RandomIDCard

func RandomIDCard() string

RandomIDCard 生成随机身份证号(仅用于测试)

func RandomName

func RandomName() string

RandomName 生成随机姓名(中文)

func RandomPhone

func RandomPhone() string

RandomPhone 生成随机手机号(中国大陆)

func RegisterGenerator

func RegisterGenerator(name string, generator RandGeneratorFunc)

RegisterGenerator 注册自定义生成器

func UUID

func UUID() string

UUID 生成 UUID 字符串

func UnregisterGenerator

func UnregisterGenerator(name string)

UnregisterGenerator 注销生成器

Types

type DomainKeywordBuilder

type DomainKeywordBuilder struct {
	// contains filtered or unexported fields
}

DomainKeywordBuilder 域名关键词生成器(支持链式调用)

func NewDomainKeywordBuilder

func NewDomainKeywordBuilder(baseKeyword string) *DomainKeywordBuilder

NewDomainKeywordBuilder 创建域名关键词生成器 参数:

  • baseKeyword: 基础关键词(如用户搜索的词)

示例:

  • random.NewDomainKeywordBuilder("game").Generate()
  • random.NewDomainKeywordBuilder("shop").WithCount(5).WithPrefixLength(2, 4).Generate()

func (*DomainKeywordBuilder) Generate

func (b *DomainKeywordBuilder) Generate() []string

Generate 生成随机关键词组合列表

func (*DomainKeywordBuilder) GenerateAndJoinWithTLDs

func (b *DomainKeywordBuilder) GenerateAndJoinWithTLDs(tlds []string, separator string) string

GenerateAndJoinWithTLDs 生成关键词、拼接TLD并用分隔符连接 参数:

  • tlds: TLD列表,如 ["com", "net", "org"]
  • separator: 连接符,如 "," 或 ";"

返回:

  • string: 连接后的字符串

示例:

  • NewDomainKeywordBuilder("game").WithCount(2).GenerateAndJoinWithTLDs([]string{"com", "net"}, ",") -> "ab1game23.com,ab1game23.net,xy5game67.com,xy5game67.net"

func (*DomainKeywordBuilder) WithCount

func (b *DomainKeywordBuilder) WithCount(count int) *DomainKeywordBuilder

WithCount 设置生成的关键词数量

func (*DomainKeywordBuilder) WithMaxBaseKeywordLength

func (b *DomainKeywordBuilder) WithMaxBaseKeywordLength(maxLen int) *DomainKeywordBuilder

WithMaxBaseKeywordLength 设置 baseKeyword 的最大长度 如果 baseKeyword 超过此长度,将从随机位置截取

func (*DomainKeywordBuilder) WithPrefixLength

func (b *DomainKeywordBuilder) WithPrefixLength(min, max int) *DomainKeywordBuilder

WithPrefixLength 设置前缀长度范围

func (*DomainKeywordBuilder) WithSuffixLength

func (b *DomainKeywordBuilder) WithSuffixLength(min, max int) *DomainKeywordBuilder

WithSuffixLength 设置后缀长度范围

type GenerateRandModelOptions

type GenerateRandModelOptions struct {
	MaxDepth      int  // 最大递归深度,防止无限嵌套
	MaxSliceLen   int  // 切片最大长度
	MaxMapLen     int  // 映射最大长度
	StringLength  int  // 字符串长度
	FillNilPtr    bool // 是否填充 nil 指针
	UseCustomTags bool // 是否使用自定义标签
}

func DefaultOptions

func DefaultOptions() *GenerateRandModelOptions

DefaultOptions 返回默认选项

type RandGeneratorFunc

type RandGeneratorFunc func() interface{}

RandGeneratorFunc 自定义随机数据生成器函数类型

func GetGenerator

func GetGenerator(name string) (RandGeneratorFunc, bool)

GetGenerator 获取已注册的生成器

type RandGeneratorRegistry

type RandGeneratorRegistry struct {
	// contains filtered or unexported fields
}

RandGeneratorRegistry 随机数据生成器注册表

type RandType

type RandType int
const (
	// CAPITAL 包含大写字母
	CAPITAL RandType = 1 << iota // 自定义扩展
	// LOWERCASE 包含小写字母
	LOWERCASE
	// SPECIAL 包含特殊字符
	SPECIAL
	// NUMBER 包含数字
	NUMBER
)

type SurnameInfo

type SurnameInfo struct {
	Surname       string   // 姓氏的汉字,例如“赵”、“钱”等
	Initial       string   // 姓氏拼音的首字母,方便快速索引或分类
	CorrectPinyin string   // 姓氏的标准拼音(通常为主要读音),例如 "zhao"
	AllPinyins    []string // 姓氏所有可能的拼音读法(多音字情况),例如 []string{"zhào", "zhao"}
}

SurnameInfo 表示一个姓氏的详细信息

type SurnameManager

type SurnameManager struct {
	// contains filtered or unexported fields
}

SurnameManager 管理一组姓氏信息,提供过滤、查询等功能

func NewSurnameManager

func NewSurnameManager(data ...[]SurnameInfo) *SurnameManager

NewSurnameManager 创建一个新的 SurnameManager,可选传入额外的姓氏数据,会追加到默认数据后面

func (*SurnameManager) AppendData

func (m *SurnameManager) AppendData(newData ...SurnameInfo)

AppendData 向当前管理器追加姓氏数据

func (*SurnameManager) Data

func (m *SurnameManager) Data() []SurnameInfo

Data 返回当前管理器持有的所有姓氏数据切片

func (*SurnameManager) FilterByPinyin

func (m *SurnameManager) FilterByPinyin(pinyin string) *SurnameManager

按拼音过滤,返回新的管理器

func (*SurnameManager) FilterBySurname

func (m *SurnameManager) FilterBySurname(surname string) *SurnameManager

按姓氏汉字过滤,返回新的管理器

func (*SurnameManager) Print

func (m *SurnameManager) Print()

打印当前管理器数据

func (*SurnameManager) RandomSurname

func (m *SurnameManager) RandomSurname() (SurnameInfo, error)

RandomSurname 从管理器中随机返回一个姓氏信息

func (*SurnameManager) ToJSON

func (m *SurnameManager) ToJSON() (string, error)

导出当前管理器数据为JSON字符串

Jump to

Keyboard shortcuts

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