gotool

package module
v0.0.0-...-fb310ff Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2025 License: MIT Imports: 35 Imported by: 0

README

gotool Package

Gotool is a Go package that provides useful utility functions for common tasks such as generating random values, working with IP addresses and manipulating dates.

Installation

To use Gotool, you can simply import it in your Go project:

import "github.com/supernarsi/gotool"

Then, install the package by running:

go get github.com/supernarsi/gotool

Usage

Random

Gotool provides functions for generating random integers, booleans, and strings.

License

Gotool is released under the MIT License. See LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	InvCodePrime1 = 3          // 与字符集长度 62 互质
	InvCodePrime2 = 5          // 与邀请码长度 6 互质
	InvCodeSalt   = 4213098675 // 随意取一个数值
)

Variables

View Source
var (
	ErrInvalidBase64 = errors.New("invalid base64 string")
	ErrInvalidRegex  = errors.New("invalid regular expression")
)

Functions

func AppendStringToFile

func AppendStringToFile(filename, content string) error

AppendStringToFile 将字符串追加到文件末尾

func AssignGroup

func AssignGroup(id uint32, seed uint32) uint32

AssignGroup 使用 Murmur3 哈希算法分配组

func Base64ToString

func Base64ToString(s string) (string, error)

Base64ToString decodes a Base64 string

func CalSwitchRemain

func CalSwitchRemain(lastTime int, cd int) int

func CheckPasswordHash

func CheckPasswordHash(password, hash string) bool

CheckPasswordHash 校验密码与 hash

func Compare

func Compare(v1, v2 string) int

Compare 比较格式为 X.Y.Z 的版本号的大小关系(X、Y、Z 为纯数字) 返回值:0 表示v1与v2相等;1 表示v1大于v2;2 表示v1小于v2;-1 表示版本号格式错误

func CopyFile

func CopyFile(src, dst string) error

CopyFile 复制文件

func CreateDirIfNotExist

func CreateDirIfNotExist(path string) error

CreateDirIfNotExist 如果目录不存在则创建

func Difference

func Difference[T ElementType](slice1, slice2 []T) []T

Difference 计算两个切片的差集

func DirExists

func DirExists(path string) bool

DirExists 检查目录是否存在

func FileExists

func FileExists(filename string) bool

FileExists 检查文件是否存在

func FindFilesByExt

func FindFilesByExt(dirPath string, ext string) ([]string, error)

FindFilesByExt 查找指定目录下所有具有特定扩展名的文件

func FloatRatioToInt

func FloatRatioToInt(input []float32) []int

FloatRatioToInt 将浮点数数组转换为整数百分比(确保总和 100)

func GenerateToken

func GenerateToken(config *JWTConfig, userID uint, username string) (string, error)

GenerateToken 生成 JWT token

func GetConstellation

func GetConstellation(timestamp int64) uint

func GetFileSize

func GetFileSize(filename string) (int64, error)

GetFileSize 获取文件大小(字节数)

func GetJSON

func GetJSON(url string, v interface{}) error

GetJSON 发送GET请求并将响应解析为JSON

func GetUtilityTime

func GetUtilityTime() *utilityTime

func HashPassword

func HashPassword(password string) (string, error)

HashPassword 生成密码 hash

func InArray

func InArray[T ElementType](target T, arr []T) bool

InArray 判断元素是否在切片中

func IsEmptyDir

func IsEmptyDir(dirPath string) (bool, error)

IsEmptyDir 检查目录是否为空

func IsMultibyte

func IsMultibyte(r rune) bool

IsMultibyte 判断字符是否为多字节字符

func ListFilesInDir

func ListFilesInDir(dirPath string) ([]string, error)

ListFilesInDir 列出目录中的所有文件(不包括子目录)

func ListToMap

func ListToMap[T any, K comparable](list []T, keySelector func(T) K) map[K]T

ListToMap 泛型方法,允许自定义 key 选择

func ListToMapByField

func ListToMapByField[T any](list []T, key string) map[int]T

ListToMapByField 反射版 ListToMap,支持结构体字段作为 key

func Lottery

func Lottery(probabilities []int) int

Lottery 抽奖算法

func MaskNickname

func MaskNickname(nickname string) string

MaskNickname 隐藏昵称 - 单字节字符(如英文、数字)显示前两位,其余用星号替换 - 多字节字符(如中文、日文、韩文)显示第一位,其余用星号替换

func MergeMaps

func MergeMaps[K comparable, V any](maps ...map[K]V) map[K]V

MergeMaps 泛型合并 map,适用于所有类型的 key 和 value

func PostJSON

func PostJSON(url string, body, v interface{}) error

PostJSON 发送POST请求并将响应解析为JSON

func RandInt

func RandInt(nums []int, dayN uint, needNum int) []int

RandInt 返回打乱后的前 needNum 个元素

func RandomIdx

func RandomIdx(num int) int

RandomIdx 生成 0 到 num-1 的随机索引

func RandomReadableUniCode6Len

func RandomReadableUniCode6Len() string

RandomReadableUniCode6Len 返回可读性高的 6 位唯一码

func RandomReadableUniCode8Len

func RandomReadableUniCode8Len() string

RandomReadableUniCode8Len 返回可读性高的 8 位唯一码

func RandomStrictUniCode8Len

func RandomStrictUniCode8Len() string

RandomStrictUniCode8Len 返回严格不重复的 8 位唯一码

func RandomString

func RandomString(n int) string

RandomString 随机生成指定长度的十六进制字符串 输入长度 n 会被转换为最接近的偶数(向下取整) 例如:输入1或2返回2位字符,输入3或4返回4位字符 RandomString 随机生成 n 位字符串

func RandomUniCode

func RandomUniCode(longCode bool, readability bool) (string, error)

RandomUniCode 随机生成 6 或 8 位不重复(非严格意义)字符串 longCode 为 true 时返回 8 位长度;false 时返回 6 位 readability 为 true 时返回只包含数字和大写字母(排除 0、O、1、I);为 false 时返回可能包含所有数字和大小写字母

重复概率参考数据: [longCode == false && readability == true]

  • 连续生成 10 万次,约 5 次重复;
  • 连续生成 100 万次,约 500 次重复;
  • 连续生成 1000 万次,约 50000 次重复

[longCode == false && readability == false]

  • 连续生成 10 万次,约 <1 次重复;
  • 连续生成 100 万次,约 10 次重复;
  • 连续生成 1000 万次,约 1000 次重复

[longCode == true && readability == true]

  • 连续生成 10 万次,约 <1 次重复;
  • 连续生成 100 万次,约 <1 次重复;
  • 连续生成 1000 万次,约 <50 次重复

[longCode == true && readability == false]

  • 理论上不重复(与 uuid 一一对应)

func ReadFileToString

func ReadFileToString(filename string) (string, error)

ReadFileToString 安全地读取文件内容到字符串

func ReadJSONFile

func ReadJSONFile(filename string, v interface{}) error

ReadJSONFile 从JSON文件读取数据到结构体

func ReadLines

func ReadLines(filename string) ([]string, error)

ReadLines 读取文件的所有行

func RefreshToken

func RefreshToken(config *JWTConfig, tokenString string) (string, error)

RefreshToken 刷新 JWT token

func SafeRemove

func SafeRemove(path string) error

SafeRemove 安全删除文件或空目录

func SampleGenerateCode

func SampleGenerateCode(codeLength int) (string, error)

func StringCamelToPascal

func StringCamelToPascal(s string) string

StringCamelToPascal converts a camelCase string to PascalCase

func StringCamelToSnake

func StringCamelToSnake(s string) string

StringCamelToSnake converts a camelCase string to snake_case

func StringContainsAll

func StringContainsAll(s string, substrings ...string) bool

StringContainsAll checks if a string contains all of the provided substrings

func StringContainsAny

func StringContainsAny(s string, substrings ...string) bool

StringContainsAny checks if a string contains any of the provided substrings

func StringCountWords

func StringCountWords(s string) int

StringCountWords counts the number of words in a string

func StringExtractAllByRegex

func StringExtractAllByRegex(s, pattern string) ([][]string, error)

StringExtractAllByRegex extracts all matches from a string using a regular expression

func StringExtractByRegex

func StringExtractByRegex(s, pattern string) ([]string, error)

StringExtractByRegex extracts content from a string using a regular expression

func StringFormatByteSize

func StringFormatByteSize(bytes int64) string

StringFormatByteSize formats a byte size into a human-readable string

func StringIsEmpty

func StringIsEmpty(s string) bool

StringIsEmpty checks if a string is empty or contains only whitespace

func StringIsMatch

func StringIsMatch(s, pattern string) (bool, error)

StringIsMatch checks if a string matches the provided regular expression pattern

func StringIsNotEmpty

func StringIsNotEmpty(s string) bool

StringIsNotEmpty checks if a string is not empty and contains non-whitespace characters

func StringJoinWithSeparator

func StringJoinWithSeparator(sep string, parts ...string) string

StringJoinWithSeparator joins strings with a separator, ignoring empty strings

func StringMaskEmail

func StringMaskEmail(email string) string

StringMaskEmail masks an email address for privacy

func StringMaskPhone

func StringMaskPhone(phone string) string

StringMaskPhone masks a phone number for privacy

func StringPascalToCamel

func StringPascalToCamel(s string) string

StringPascalToCamel converts a PascalCase string to camelCase

func StringRemoveDuplicates

func StringRemoveDuplicates(slice []string) []string

StringRemoveDuplicates removes duplicate strings from a slice while preserving order

func StringReplaceAll

func StringReplaceAll(s string, replacements map[string]string) string

StringReplaceAll replaces multiple substrings in a string according to the provided map

func StringReverse

func StringReverse(s string) string

StringReverse reverses a string while preserving UTF-8 encoding

func StringSnakeToCamel

func StringSnakeToCamel(s string) string

StringSnakeToCamel converts a snake_case string to camelCase

func StringSplitAndTrim

func StringSplitAndTrim(s, sep string) []string

StringSplitAndTrim splits a string by the separator and trims whitespace from each part

func StringTemplate

func StringTemplate(templateStr string, data interface{}) (string, error)

StringTemplate renders a string using the provided template and data

func StringToBase64

func StringToBase64(s string) string

StringToBase64 encodes a string to Base64

func StringToMD5

func StringToMD5(s string) string

StringToMD5 calculates the MD5 hash of a string

func StringToSHA1

func StringToSHA1(s string) string

StringToSHA1 calculates the SHA1 hash of a string

func StringToSHA256

func StringToSHA256(s string) string

StringToSHA256 calculates the SHA256 hash of a string

func StringTruncate

func StringTruncate(s string, maxLen int) string

StringTruncate truncates a string to the specified maximum length and adds ellipsis If maxLen is less than or equal to 3, it will simply truncate without ellipsis

func TempFile

func TempFile(dir, pattern string) (*os.File, error)

TempFile 创建临时文件并返回其文件句柄

func UniInvCodeLen6ByUID

func UniInvCodeLen6ByUID(uid uint64, baseChars []byte) (string, error)

func UniqueElements

func UniqueElements[T ElementType](elements []T) []T

UniqueElements 过滤切片中的重复元素

func ValidateToken

func ValidateToken(config *JWTConfig, tokenString string) bool

ValidateToken 验证 JWT token 是否有效

func VerCompare

func VerCompare(v1, v2, operator string) bool

VerCompare 比较 v1、v2 的版本号大小

func WalkDir

func WalkDir(dirPath string, callback func(path string, info os.FileInfo) error) error

WalkDir 递归遍历目录,对每个文件执行回调函数

func WriteJSONFile

func WriteJSONFile(filename string, v interface{}, pretty bool) error

WriteJSONFile 将结构体数据写入JSON文件

func WriteLines

func WriteLines(filename string, lines []string) error

WriteLines 将字符串切片写入文件,每行一个字符串

func WriteStringToFile

func WriteStringToFile(filename, content string) error

WriteStringToFile 安全地将字符串写入文件

Types

type ElementType

type ElementType interface{ eleNum | string }

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient 是HTTP客户端的接口定义

type HTTPRequest

type HTTPRequest struct {
	URL         string
	Method      string
	Headers     map[string]string
	QueryParams map[string]string
	Body        interface{}
	Timeout     time.Duration
	Client      HTTPClient
	Context     context.Context
}

HTTPRequest 封装HTTP请求的参数

func NewHTTPRequest

func NewHTTPRequest() *HTTPRequest

NewHTTPRequest 创建一个新的HTTP请求

func (*HTTPRequest) Send

func (r *HTTPRequest) Send() *HTTPResponse

Send 发送HTTP请求

func (*HTTPRequest) SetBody

func (r *HTTPRequest) SetBody(body interface{}) *HTTPRequest

SetBody 设置请求体

func (*HTTPRequest) SetClient

func (r *HTTPRequest) SetClient(client HTTPClient) *HTTPRequest

SetClient 设置HTTP客户端

func (*HTTPRequest) SetContext

func (r *HTTPRequest) SetContext(ctx context.Context) *HTTPRequest

SetContext 设置上下文

func (*HTTPRequest) SetHeader

func (r *HTTPRequest) SetHeader(key, value string) *HTTPRequest

SetHeader 设置单个请求头

func (*HTTPRequest) SetHeaders

func (r *HTTPRequest) SetHeaders(headers map[string]string) *HTTPRequest

SetHeaders 批量设置请求头

func (*HTTPRequest) SetMethod

func (r *HTTPRequest) SetMethod(method string) *HTTPRequest

SetMethod 设置HTTP方法

func (*HTTPRequest) SetQueryParam

func (r *HTTPRequest) SetQueryParam(key, value string) *HTTPRequest

SetQueryParam 设置单个查询参数

func (*HTTPRequest) SetQueryParams

func (r *HTTPRequest) SetQueryParams(params map[string]string) *HTTPRequest

SetQueryParams 批量设置查询参数

func (*HTTPRequest) SetTimeout

func (r *HTTPRequest) SetTimeout(timeout time.Duration) *HTTPRequest

SetTimeout 设置请求超时时间

func (*HTTPRequest) SetURL

func (r *HTTPRequest) SetURL(url string) *HTTPRequest

SetURL 设置请求URL

type HTTPResponse

type HTTPResponse struct {
	StatusCode int
	Headers    http.Header
	Body       []byte
	Error      error
}

HTTPResponse 封装HTTP响应

func DELETE

func DELETE(url string) *HTTPResponse

DELETE 发送DELETE请求

func GET

func GET(url string) *HTTPResponse

GET 发送GET请求

func PATCH

func PATCH(url string, body interface{}) *HTTPResponse

PATCH 发送PATCH请求

func POST

func POST(url string, body interface{}) *HTTPResponse

POST 发送POST请求

func PUT

func PUT(url string, body interface{}) *HTTPResponse

PUT 发送PUT请求

func (*HTTPResponse) IsSuccess

func (r *HTTPResponse) IsSuccess() bool

IsSuccess 检查响应是否成功(状态码2xx)

func (*HTTPResponse) JSON

func (r *HTTPResponse) JSON(v interface{}) error

JSON 将响应体解析为JSON

func (*HTTPResponse) String

func (r *HTTPResponse) String() string

String 将响应体转换为字符串

type IpDetail

type IpDetail struct {
	Ip           string
	CountryShort string
	CountryLong  string
	Province     string
	City         string
	Isp          string
	Latitude     float32
	Longitude    float32
	Zipcode      string
	Timezone     string
}

type JWTClaims

type JWTClaims struct {
	UserID   uint   `json:"user_id"`
	Username string `json:"username"`
	jwt.RegisteredClaims
}

JWTClaims 自定义的 JWT Claims 结构

func ParseToken

func ParseToken(config *JWTConfig, tokenString string) (*JWTClaims, error)

ParseToken 解析 JWT token

type JWTConfig

type JWTConfig struct {
	SecretKey     string        // JWT 密钥
	ExpireTime    time.Duration // 过期时间
	Issuer        string        // 签发者
	SigningMethod string        // 签名方法
}

JWTConfig JWT 配置结构

func DefaultJWTConfig

func DefaultJWTConfig() *JWTConfig

DefaultJWTConfig 返回默认的 JWT 配置

type SyncMap

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

func NewSyncMap

func NewSyncMap() *SyncMap

func (*SyncMap) IsExist

func (s *SyncMap) IsExist(key any) bool

func (*SyncMap) Lock

func (s *SyncMap) Lock(key any)

func (*SyncMap) Unlock

func (s *SyncMap) Unlock(key any)

Directories

Path Synopsis
geo

Jump to

Keyboard shortcuts

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