utils

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2026 License: MIT Imports: 37 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ENV_CONFIG_CACHE_SIZE    = "CONFIG_CACHE_SIZE"
	ENV_CONFIG_CACHE_EXPIRED = "CONFIG_CACHE_EXPIRED"
)
View Source
const (
	// PCONLINE_IP_URL IP地址查询API(国内)
	PCONLINE_IP_URL = "http://whois.pconline.com.cn/ipJson.jsp"
	// IP_API_URL IP地址查询API(国际)
	IP_API_URL = "http://ip-api.com/json/"
	// UNKNOWN 未知地址
	UNKNOWN = "Unknown"
	// INTERNAL_IP 内网IP标识
	INTERNAL_IP = "内网IP"
	// LOCAL_NETWORK 本地网络
	LOCAL_NETWORK = "Local Network"
)
View Source
const (
	FILE_TYPE_IMAGE int32 = 3
	FILE_TYPE_FILE  int32 = 4
	FILE_TYPE_AUDIO int32 = 5
	FILE_TYPE_MEDIA int32 = 6
)
View Source
const ENV_DB_DRIVER = "DB_DRIVER"
View Source
const ENV_DSN = "DSN"

Variables

This section is empty.

Functions

func AddDuration

func AddDuration(d time.Duration) int64

func AesDecrypt

func AesDecrypt(key, ciphertext []byte) (buf []byte, err error)

func AesEncrypt

func AesEncrypt(key, plaintext []byte) (buf []byte, err error)

func BytesToString

func BytesToString(b []byte) string

BytesToString bytes to string Zero-copy

func CalculateAge

func CalculateAge(birthday time.Time) int

func CalculateFileHash

func CalculateFileHash(filePath string) (string, error)

CalculateFileHash 计算文件的SHA1哈希

func CheckValue

func CheckValue(db *gorm.DB, key, defaultValue, format string, autoload, public bool)

func CleanText added in v0.1.1

func CleanText(s string, opts *Options) string

func ConfigureConnectionPool

func ConfigureConnectionPool(db *gorm.DB)

ConfigureConnectionPool configure database connection pool

func CopyFile

func CopyFile(src, dst string) error

CopyFile 复制文件

func Difference

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

Difference get difference set slice1-intersection

func EndOfDay

func EndOfDay(t time.Time) time.Time

func EnsureDirectory

func EnsureDirectory(path string) error

EnsureDirectory 确保目录存在

func FileExists

func FileExists(path string) bool

FileExists 检查文件是否存在

func GenerateID

func GenerateID() string

GenerateID 生成唯一的ID

func GetBoolEnv

func GetBoolEnv(key string) bool

func GetBoolValue

func GetBoolValue(db *gorm.DB, key string) bool

func GetContentType

func GetContentType(suffix string) (tp string)

func GetCrc16

func GetCrc16(val int64) uint16

func GetDistance

func GetDistance(lon1, lat1, lon2, lat2 float64) float64

GetDistance Calculate distance between two points

func GetEnv

func GetEnv(key string) string

func GetFileSize

func GetFileSize(filePath string) (int64, error)

GetFileSize 获取文件大小

func GetFileType

func GetFileType(buf []byte) (fileType string)

func GetFileTypeBySuffix

func GetFileTypeBySuffix(suffix string) int32

func GetFloatEnv

func GetFloatEnv(key string) float64

func GetFloatEnvWithDefault

func GetFloatEnvWithDefault(key string, defaultValue float64) float64

GetFloatEnvWithDefault gets float environment variable with default value

func GetIntEnv

func GetIntEnv(key string) int64

func GetIntEnvWithDefault

func GetIntEnvWithDefault(key string, defaultValue int) int

GetIntEnvWithDefault gets int environment variable with default value

func GetIntValue

func GetIntValue(db *gorm.DB, key string, defaultVal int) int

func GetLocationByIP

func GetLocationByIP(ip string) (country, city, location string)

GetLocationByIP 根据IP获取地理位置信息(国家、城市、完整位置)

func GetLocationByIPWithPconline

func GetLocationByIPWithPconline(ip string) (country, city, location string)

GetLocationByIPWithPconline 使用pconline API获取IP地理位置(国内IP更准确)

func GetRealAddressByIP

func GetRealAddressByIP(ip string) string

GetRealAddressByIP 根据IP获取真实地址(兼容旧接口,返回完整地址字符串)

func GetValue

func GetValue(db *gorm.DB, key string) string

func InArray

func InArray[T comparable](needle T, haystack []T) bool

InArray check if element is in array

func InitDatabase

func InitDatabase(logWrite io.Writer, driver, dsn string) (*gorm.DB, error)

func InitGlobalCache

func InitGlobalCache(maxSize int, expiration time.Duration)

func Intersect

func Intersect[T comparable](slice1, slice2 []T) []T

Intersect get intersection

func IsDirectory

func IsDirectory(path string) bool

IsDirectory 检查路径是否为目录

func IsFile

func IsFile(path string) bool

IsFile 检查路径是否为文件

func IsInternalIP

func IsInternalIP(ip string) bool

IsInternalIP 判断是否为内网IP

func Join

func Join[T any](arg []T, str string) string

func LoadAutoloads

func LoadAutoloads(db *gorm.DB)

func LoadEnv

func LoadEnv(env string) error

LoadEnv Load .env file based on environment

func LoadEnvs

func LoadEnvs(objPtr any)

load envs to struct

func LookupEnv

func LookupEnv(key string) (value string, found bool)

func MD5

func MD5(str string) string

func MakeMigrates

func MakeMigrates(db *gorm.DB, insts []any) error

func Merge

func Merge[T any](slice1, slice2 []T) []T

Merge get union

func MillisFromTime

func MillisFromTime(t time.Time) int64

func NowUnix

func NowUnix() int64

func RC4Decrypt

func RC4Decrypt(str string, key []byte) string

func RC4Encrypt

func RC4Encrypt(str string, key []byte) string

func ReadFile

func ReadFile(filename string) ([]byte, error)

ReadFile read file

func RemoveDirectory

func RemoveDirectory(path string) error

RemoveDirectory 删除目录

func RemoveFile

func RemoveFile(path string) error

RemoveFile 删除文件

func SetIPServiceLogger

func SetIPServiceLogger(logger *zap.Logger)

SetIPServiceLogger 设置IP服务的logger

func SetIPServiceTimeout

func SetIPServiceTimeout(timeout time.Duration)

SetIPServiceTimeout 设置IP服务的超时时间

func SetValue

func SetValue(db *gorm.DB, key, value, format string, autoload, public bool)

func SixteenMD5

func SixteenMD5(str string) string

func StartOfDay

func StartOfDay(t time.Time) time.Time

func StringToBytes

func StringToBytes(s string) []byte

StringToBytes string to bytes Zero-copy

func TimeFromMillis

func TimeFromMillis(millis int64) time.Time

func UnZlib

func UnZlib(in []byte) (out []byte)

func Unique

func Unique[T comparable](slice []T) []T

Unique remove duplicates from array

func WriteFile

func WriteFile(filename string, data []byte) error

WriteFile write file

func Yesterday

func Yesterday() time.Time

func Zlib

func Zlib(in []byte) (out []byte)

Types

type Config

type Config struct {
	ID        uint   `json:"id" gorm:"primaryKey"`
	Key       string `json:"key" gorm:"size:128;uniqueIndex"`
	Desc      string `json:"desc" gorm:"size:200"`
	Autoload  bool   `json:"autoload" gorm:"index"`
	Public    bool   `json:"public" gorm:"index" default:"false"`
	Format    string `json:"format" gorm:"size:20" default:"text" comment:"json,yaml,int,float,bool,text"`
	Value     string
	CreatedAt time.Time `json:"-" gorm:"autoCreateTime"`
	UpdatedAt time.Time `json:"-" gorm:"autoUpdateTime"`
}

func LoadPublicConfigs

func LoadPublicConfigs(db *gorm.DB) []Config

type ExpiredLRUCache

type ExpiredLRUCache[K comparable, V any] struct {
	*lru.Cache[K, expiredLRUCacheValue[V]]
	// contains filtered or unexported fields
}
var GlobalCache *ExpiredLRUCache[string, any]

GlobalCache is a global cache instance that supports generic key-value pairs

func NewExpiredLRUCache

func NewExpiredLRUCache[K comparable, V any](size int, expired time.Duration) *ExpiredLRUCache[K, V]

func (*ExpiredLRUCache[K, V]) Add

func (c *ExpiredLRUCache[K, V]) Add(key K, value V) (evicted bool)

func (*ExpiredLRUCache[K, V]) Contains

func (c *ExpiredLRUCache[K, V]) Contains(key K) bool

func (*ExpiredLRUCache[K, V]) Get

func (c *ExpiredLRUCache[K, V]) Get(key K) (value V, ok bool)

func (*ExpiredLRUCache[K, V]) Remove

func (c *ExpiredLRUCache[K, V]) Remove(key K) (present bool)

type IPGeolocationResponse

type IPGeolocationResponse struct {
	Country     string  `json:"country"`
	CountryCode string  `json:"countryCode"`
	Region      string  `json:"region"`
	City        string  `json:"city"`
	Lat         float64 `json:"lat"`
	Lon         float64 `json:"lon"`
	Timezone    string  `json:"timezone"`
	ISP         string  `json:"isp"`
	Org         string  `json:"org"`
	AS          string  `json:"as"`
	Query       string  `json:"query"`
	Status      string  `json:"status"`
	Message     string  `json:"message"`
}

IPGeolocationResponse IP地理位置API响应(ip-api格式)

type IPLocationResponse

type IPLocationResponse struct {
	Pro  string `json:"pro"`  // 省份
	City string `json:"city"` // 城市
}

IPLocationResponse IP地理位置查询响应结构(pconline格式)

type IPLocationService

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

IPLocationService IP地理位置服务

func NewIPLocationService

func NewIPLocationService(logger *zap.Logger) *IPLocationService

NewIPLocationService 创建IP地理位置服务

func NewIPLocationServiceWithPconline

func NewIPLocationServiceWithPconline(logger *zap.Logger) *IPLocationService

NewIPLocationServiceWithPconline 创建使用pconline API的IP地理位置服务(国内IP更准确)

func (*IPLocationService) GetLocation

func (ils *IPLocationService) GetLocation(ip string) (country, city, location string, err error)

GetLocation 获取IP地理位置(返回国家、城市、完整位置字符串)

type Options added in v0.1.1

type Options struct {
	Lowercase            bool
	StripMarkdown        bool
	StripSymbols         bool
	DedupLines           bool
	DropBoilerplateLines bool
}

type Snowflake

type Snowflake struct {
	// contains filtered or unexported fields
}
var SnowflakeUtil *Snowflake

func NewSnowflake

func NewSnowflake() (*Snowflake, error)

func (*Snowflake) GenID

func (sf *Snowflake) GenID() string

GenID 字符串格式(正数)

func (*Snowflake) NextID

func (sf *Snowflake) NextID() int64

NextID 生成 唯一 正数 int64

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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