Documentation
¶
Index ¶
- Variables
- func AddHeader(w http.ResponseWriter, key, value string)
- func Base64Decode(str string) (string, error)
- func Base64Encode(str string) string
- func BuildQueryString(params map[string]string) string
- func BuildURL(scheme, host, path string, query map[string]string) string
- func BuildYii2RedisCacheKey(key string, args ...string) string
- func CalculateAge(args ...interface{}) (int, error)
- func CheckAndSetDefault(i interface{}) error
- func CheckAndSetDefaultWithPreserveTag(i interface{}) error
- func CheckETag(req *http.Request, etag string) bool
- func CompareNumber(a, b interface{}) int
- func CompareVersion(a string, b string) (result int, level int)
- func ConvertUnit(value float64, fromUnit, toUnit string, unitType UnitType) (float64, error)
- func CopyStruct(src, dst interface{})
- func DownloadFile(url, filepath string) error
- func ExtractDomain(urlStr string) (string, error)
- func ExtractHeaders(header http.Header) map[string]string
- func ExtractPath(urlStr string) (string, error)
- func ExtractQueryParams(urlStr string) (map[string]string, error)
- func FindAvailablePort(startPort string) string
- func FormatHeaders(headers map[string]string) string
- func FormatUnit(value interface{}, unitType UnitType, precision int, toUnit ...string) (string, error)
- func GenerateETag(content []byte) string
- func GenerateSSHKey() error
- func GetAvailableUnits(unitType UnitType) []string
- func GetCookie(req *http.Request, name string) string
- func GetFieldNameByJSONTag(objType reflect.Type, jsonKey string) string
- func GetFileExtension(filename string) string
- func GetFormFile(req *http.Request, key string) (multipart.File, *multipart.FileHeader, error)
- func GetFormValue(req *http.Request, key string) string
- func GetFullURL(req *http.Request) string
- func GetHTTP(url string, headers map[string]string) (*http.Response, error)
- func GetHTTPStatusText(code int) string
- func GetHeader(req *http.Request, key string) string
- func GetHostInfo(req *http.Request) string
- func GetHostname(req *http.Request) string
- func GetMimeType(extension string) string
- func GetPort(req *http.Request) string
- func GetQueryParam(req *http.Request, key string) string
- func GetQueryParams(req *http.Request) map[string][]string
- func GetRealIPFromHeaders(headers map[string]string) string
- func GetSSHKey() (string, error)
- func GetValidClientIP(ips []string) string
- func InArray(val interface{}, array interface{}) (exists bool)
- func IsAjaxRequest(req *http.Request) bool
- func IsBotUserAgent(userAgent string) bool
- func IsEmptyValue(val interface{}) bool
- func IsError(errs []error) bool
- func IsFormRequest(req *http.Request) bool
- func IsHTTPS(req *http.Request) bool
- func IsJSONRequest(req *http.Request) bool
- func IsMobileUserAgent(userAgent string) bool
- func IsURLSecure(urlStr string) bool
- func IsValidUnit(unitStr string, unitType UnitType) bool
- func MapToStruct(mapData interface{}, obj interface{})
- func MatchWildcard(pattern, s string, caseSensitive bool) bool
- func Max(numbers ...interface{}) interface{}
- func Min(numbers ...interface{}) interface{}
- func NewHTTPClient(config *HTTPClientConfig) *http.Client
- func NormalizeURL(urlStr string) (string, error)
- func ParseChineseIDCard(idCard string) (gender string, age int, birthDay string, regionCode string, ...)
- func ParseIP(s string) (net.IP, int)
- func ParseMultipartForm(req *http.Request, maxMemory int64) error
- func ParseQueryString(query string) map[string]string
- func PostFormHTTP(urlStr string, data map[string]string, headers map[string]string) (*http.Response, error)
- func PostHTTP(url string, body []byte, headers map[string]string) (*http.Response, error)
- func Random(length int, args ...bool) string
- func ReadResponseBody(resp *http.Response) ([]byte, error)
- func ReadResponseBodyString(resp *http.Response) (string, error)
- func Redirect(w http.ResponseWriter, req *http.Request, url string, code int)
- func RoundUnitValue(value float64, unit string, precision int, unitType UnitType) (float64, error)
- func SaveUploadedFile(fileHeader *multipart.FileHeader, dst string) error
- func SendHTTPRequest(config *HTTPRequestConfig) (*http.Response, error)
- func SetCacheHeaders(w http.ResponseWriter, maxAge int, public bool)
- func SetContentDisposition(w http.ResponseWriter, filename, dispositionType string)
- func SetContentType(w http.ResponseWriter, contentType string)
- func SetHTMLContentType(w http.ResponseWriter)
- func SetHeader(w http.ResponseWriter, key, value string)
- func SetJSONContentType(w http.ResponseWriter)
- func SetNoCacheHeaders(w http.ResponseWriter)
- func SetStatusCode(w http.ResponseWriter, code int)
- func SetTextContentType(w http.ResponseWriter)
- func SplitAndValidateIPs(s string) []string
- func SplitIPs(s string) []string
- func StrReplace(search interface{}, replace interface{}, subject interface{}, count int) (interface{}, error)
- func StringEndWith(str, suffix string) bool
- func StringStartWith(str, prefix string) bool
- func StructMerge(dst interface{}, src ...interface{}) error
- func StructToMap(obj interface{}, useJsonTag bool) map[string]interface{}
- func TraceCaller()
- func URLDecode(s string) (string, error)
- func URLEncode(s string) string
- func ValidateURL(urlStr string) bool
- func WriteHTML(w http.ResponseWriter, html string) (int, error)
- func WriteHTMLWithStatus(w http.ResponseWriter, code int, html string) (int, error)
- func WriteJSON(w http.ResponseWriter, data interface{}) error
- func WriteJSONWithStatus(w http.ResponseWriter, code int, data interface{}) error
- func WriteString(w http.ResponseWriter, s string) (int, error)
- func WriteStringWithStatus(w http.ResponseWriter, code int, s string) (int, error)
- type ArrStr
- type Convert
- func (c Convert) ToArrByte() []byte
- func (c Convert) ToBool() bool
- func (c Convert) ToDuration() time.Duration
- func (c Convert) ToFileMode() os.FileMode
- func (c Convert) ToFloat64() float64
- func (c Convert) ToInt() int
- func (c Convert) ToInt8() int8
- func (c Convert) ToInt64() int64
- func (c Convert) ToInterface() interface{}
- func (c Convert) ToMap() map[string]interface{}
- func (c Convert) ToMapString() map[string]string
- func (c Convert) ToNumber() (interface{}, bool)
- func (c Convert) ToReflectValue(t reflect.Type) (reflect.Value, bool)
- func (c Convert) ToSlice() []interface{}
- func (c Convert) ToString() string
- func (c Convert) ToTime() time.Time
- func (c Convert) ToUint() uint
- func (c Convert) ToUint64() uint64
- type File
- func (fh *File) Basename(suffix string) string
- func (fh *File) CopyFile(targetPath string, overwrite bool, copyAttr bool) error
- func (fh *File) CopyFileAttr(targetFile string) error
- func (fh *File) CreateFile(content []byte, overwrite bool) error
- func (fh *File) DirExists(createIfNotExists bool) (exists bool, err error)
- func (fh *File) DirName() string
- func (fh *File) Exists() bool
- func (fh *File) GetAbsPath() (string, error)
- func (fh *File) IsDir() bool
- func (fh *File) IsEmpty() bool
- func (fh *File) IsEmptyDir() bool
- func (fh *File) IsEmptyFile() bool
- func (fh *File) IsExecutable() bool
- func (fh *File) IsFile() bool
- func (fh *File) IsHidden() bool
- func (fh *File) IsReadable() bool
- func (fh *File) IsSymlink() bool
- func (fh *File) IsWritable() bool
- func (fh *File) JsonToData(data *interface{}) error
- func (fh *File) Remove() error
- type HTTPClientConfig
- type HTTPRequestConfig
- type IP
- type JsonHelper
- func (jh *JsonHelper) Errors() []error
- func (jh *JsonHelper) HasError() bool
- func (jh *JsonHelper) MakeFile(filepath string) *JsonHelper
- func (jh *JsonHelper) ToFile() *JsonHelper
- func (jh *JsonHelper) ToMap(newMap *map[string]interface{}) *JsonHelper
- func (jh *JsonHelper) ToString(newStr *string) *JsonHelper
- func (jh *JsonHelper) ToStruct(newStruct interface{}) *JsonHelper
- type MapHelper
- func (d *MapHelper) ArrayKeys() []string
- func (d *MapHelper) ArrayValues() []interface{}
- func (d *MapHelper) DoSort() *MapHelper
- func (d *MapHelper) Extract(path string, defaultVal ...interface{}) interface{}
- func (d *MapHelper) ExtractBool(path string, defaultVal ...bool) bool
- func (d *MapHelper) ExtractFloat64(path string, defaultVal ...float64) float64
- func (d *MapHelper) ExtractInt(path string, defaultVal ...int) int
- func (d *MapHelper) ExtractInt64(path string, defaultVal ...int64) int64
- func (d *MapHelper) ExtractString(path string, defaultVal ...string) string
- func (d *MapHelper) ExtractStringSlice(path string, defaultVal ...[]string) []string
- func (d *MapHelper) ExtractTime(path string, defaultVal ...time.Time) time.Time
- func (d *MapHelper) GetData() map[string]interface{}
- type MoneyHelper
- func (m *MoneyHelper) Add(other *MoneyHelper) *MoneyHelper
- func (m *MoneyHelper) Divide(divisor float64) *MoneyHelper
- func (m *MoneyHelper) Equals(other *MoneyHelper) bool
- func (m *MoneyHelper) FloatString(parts ...string) string
- func (m *MoneyHelper) GetError() error
- func (m *MoneyHelper) GreaterThan(other *MoneyHelper) bool
- func (m *MoneyHelper) LessThan(other *MoneyHelper) bool
- func (m *MoneyHelper) Multiply(factor float64) *MoneyHelper
- func (m *MoneyHelper) SetAmount(value interface{}) *MoneyHelper
- func (m *MoneyHelper) Subtract(other *MoneyHelper) *MoneyHelper
- type Str
- func (s *Str) Base64UrlDecode() (string, error)
- func (s *Str) Base64UrlEncode() string
- func (s *Str) ByteLength() int
- func (s *Str) ByteSubstr(start int, length int) string
- func (s *Str) ConvertBetweenUnits(value float64, fromUnit, toUnit string, unitType UnitType) (*Str, error)
- func (s *Str) ConvertCamelToSnake() string
- func (s *Str) CountWords() int
- func (s *Str) EndsWith(suffix string, caseSensitive bool) bool
- func (s *Str) EscapeHTML() string
- func (s *Str) Explode(delimiter string, trim bool, skipEmpty bool) []string
- func (s *Str) FloatToString() *Str
- func (s *Str) FormatAsUnit(value float64, unitType UnitType, precision int, toUnit ...string) *Str
- func (s *Str) GetUnitTypeFromString(unitType UnitType) (UnitType, error)
- func (s *Str) IsUnitString(unitType UnitType) bool
- func (s *Str) MbUcFirst() string
- func (s *Str) MbUcWords() string
- func (s *Str) ParseUnit(unitType UnitType) (float64, *Unit, error)
- func (s *Str) SetFloat64(number float64) *Str
- func (s *Str) StartsWith(prefix string, caseSensitive bool) bool
- func (s *Str) ToLower() string
- func (s *Str) ToUnitValue(unitType UnitType) (float64, error)
- func (s *Str) ToUpper() string
- func (s *Str) Trim(cutSet string) string
- func (s *Str) TrimSpace() string
- func (s *Str) Truncate(length int, suffix string) string
- func (s *Str) TruncateWords(count int, suffix string) string
- type Unit
- type UnitType
Constants ¶
This section is empty.
Variables ¶
var ( // StorageUnits 存储单位映射 // StorageUnits storage unit mapping StorageUnits = []Unit{ {"Byte", []string{"B", "byte", "bytes"}, 1, UnitTypeStorage}, {"Kilobyte", []string{"KB", "K", "kilobyte", "kilobytes"}, 1024, UnitTypeStorage}, {"Megabyte", []string{"MB", "M", "megabyte", "megabytes"}, 1024 * 1024, UnitTypeStorage}, {"Gigabyte", []string{"GB", "G", "gigabyte", "gigabytes"}, 1024 * 1024 * 1024, UnitTypeStorage}, {"Terabyte", []string{"TB", "T", "terabyte", "terabytes"}, 1024 * 1024 * 1024 * 1024, UnitTypeStorage}, {"Petabyte", []string{"PB", "P", "petabyte", "petabytes"}, 1024 * 1024 * 1024 * 1024 * 1024, UnitTypeStorage}, } // TimeUnits 时间单位映射 // TimeUnits time unit mapping TimeUnits = []Unit{ {"Nanosecond", []string{"ns", "nanosecond", "nanoseconds"}, 1, UnitTypeTime}, {"Microsecond", []string{"μs", "us", "microsecond", "microseconds"}, 1000, UnitTypeTime}, {"Millisecond", []string{"ms", "millisecond", "milliseconds"}, 1000 * 1000, UnitTypeTime}, {"Second", []string{"s", "sec", "second", "seconds"}, 1000 * 1000 * 1000, UnitTypeTime}, {"Minute", []string{"m", "min", "minute", "minutes"}, 60 * 1000 * 1000 * 1000, UnitTypeTime}, {"Hour", []string{"h", "hr", "hour", "hours"}, 60 * 60 * 1000 * 1000 * 1000, UnitTypeTime}, {"Day", []string{"d", "day", "days"}, 24 * 60 * 60 * 1000 * 1000 * 1000, UnitTypeTime}, } // DataUnits 数据单位映射 // DataUnits data unit mapping DataUnits = []Unit{ {"Bit", []string{"b", "bit", "bits"}, 1, UnitTypeData}, {"Byte", []string{"byte", "bytes"}, 8, UnitTypeData}, {"Kilobit", []string{"Kb", "Kbit", "kilobit", "kilobits"}, 1024, UnitTypeData}, {"Kilobyte", []string{"Kbyte", "kilobyte", "kilobytes"}, 1024 * 8, UnitTypeData}, {"Megabit", []string{"Mb", "Mbit", "megabit", "megabits"}, 1024 * 1024, UnitTypeData}, {"Megabyte", []string{"Mbyte", "megabyte", "megabytes"}, 1024 * 1024 * 8, UnitTypeData}, {"Gigabit", []string{"Gb", "Gbit", "gigabit", "gigabits"}, 1024 * 1024 * 1024, UnitTypeData}, {"Gigabyte", []string{"Gbyte", "gigabyte", "gigabytes"}, 1024 * 1024 * 1024 * 8, UnitTypeData}, } // AllUnits 所有单位的合并映射 // AllUnits combined mapping of all units AllUnits = append(append(append([]Unit{}, StorageUnits...), TimeUnits...), DataUnits...) )
预定义的单位映射 Predefined unit mappings
Functions ¶
func AddHeader ¶ added in v0.13.5
func AddHeader(w http.ResponseWriter, key, value string)
AddHeader 添加HTTP响应头 参数:
- w: HTTP响应写入器
- key: 头信息键名
- value: 头信息值
func BuildQueryString ¶ added in v0.13.5
BuildQueryString 构建查询字符串 参数:
- params: 参数映射
返回值:
- string: 查询字符串
func BuildURL ¶ added in v0.13.5
BuildURL 构建URL 参数:
- scheme: 协议
- host: 主机
- path: 路径
- query: 查询参数
返回值:
- string: 构建的URL
func BuildYii2RedisCacheKey ¶ added in v0.10.2
BuildYii2RedisCacheKey 生成一个规范化的缓存键,支持可选的前缀参数。 逻辑同yii2的yii\caching\Cache::buildKey
参数说明: - key: 需要规范化的缓存键字符串。 - args: 可选参数,args[0] 为缓存键的前缀字符串。
处理逻辑:
- 如果 key 只包含字母和数字,且长度不超过 32 个字符, 则直接返回前缀加 key。
- 否则对 key 进行 MD5 哈希处理, 返回前缀加哈希字符串,保证缓存键长度和格式统一。
该方法适用于缓存键的标准化处理,避免因 key 格式差异导致缓存失效。
func CalculateAge ¶ added in v0.8.0
CalculateAge 计算年龄的多功能方法 支持以下两种调用方式: 1. CalculateAge(year, month, day int) (int, error) 2. CalculateAge(dateString string) (int, error)
func CheckAndSetDefault ¶
func CheckAndSetDefault(i interface{}) error
CheckAndSetDefault 检查结构体中的字段是否为空,如果为空则设置为默认值 函数名:CheckAndSetDefault 参数:i interface{} — 结构体或其指针,支持一层指针传入 返回值:error — 始终返回nil;本函数不抛出解析错误,保持兼容的静默行为 异常:不触发panic(除非外部传入不可寻址的值并强制Addr) 使用说明: - 仅对以下类型在“空值”时设置默认:string、bool、int系、float32/float64、time.Duration - struct与interface字段将递归调用本函数(interface字段递归对原逻辑无实际效果,保持兼容) - default标签为空时不会报错,数值/布尔解析失败会被忽略(保持原有逻辑) 使用示例:
type AppConfig struct {
Name string `json:"name" default:"myapp"`
Enabled bool `json:"enabled" default:"true"`
Port int `json:"port" default:"8080"`
Timeout time.Duration `json:"timeout" default:"300ms"`
}
cfg := &AppConfig{}
_ = helper.CheckAndSetDefault(cfg)
常见问题:如果发现默认值赋值失败,但是又没有出现报错,可以看看是不是传递的指针的指针
func CheckAndSetDefaultWithPreserveTag ¶ added in v0.13.8
func CheckAndSetDefaultWithPreserveTag(i interface{}) error
CheckAndSetDefaultWithPreserveTag 按 `default` 标签设置默认值,同时保留带有 `preserve:"true"` 标签字段的原始值 函数名:CheckAndSetDefaultWithPreserveTag 参数:i interface{} — 结构体或其指针,支持多层指针;顶层为nil指针时直接返回 返回值:error — 当默认值解析失败、类型溢出或不支持的类型时返回错误 异常:不触发panic,本函数所有失败均以error返回 使用说明: - 为需要保留用户显式设置零值(如 bool=false)的字段添加 `preserve:"true"` 标签 - 本函数先快照这些字段的原始值,再调用 CheckAndSetDefault 设置默认值,最后恢复快照值 使用示例:
type Config struct {
EnableFeature bool `json:"enable_feature" default:"true" preserve:"true"`
}
cfg := &Config{}
_ = helper.CheckAndSetDefaultWithPreserveTag(cfg)
func CheckETag ¶ added in v0.13.5
CheckETag 检查ETag是否匹配 参数:
- req: HTTP请求对象
- etag: 当前ETag
返回值:
- bool: 如果ETag匹配返回true,否则返回false
func CompareNumber ¶
func CompareNumber(a, b interface{}) int
CompareNumber 比较两个值,如果 a < b 返回 -1,如果 a == b 返回 0,如果 a > b 返回 1,如果错误则 panic
func CompareVersion ¶ added in v0.10.7
CompareVersion 版本号比较(支持x.y.z,降级为数值分段比较,不足段补0;非法段按0处理) 参数:
- a: 版本号A
- b: 版本号B
返回:
- result: 比较结果(1 表示a>b;0表示相等;-1表示a<b)
- level: 差异级别(从1开始,表示第几级版本号差异;0表示无差异)
func ConvertUnit ¶ added in v0.13.5
ConvertUnit 在不同单位之间转换数值 ConvertUnit converts values between different units
参数:
- value: 原始数值
- fromUnit: 原始单位符号
- toUnit: 目标单位符号
- unitType: 单位类型
返回值:
- float64: 转换后的数值
- error: 转换过程中的错误
示例:
- ConvertUnit(10, "MB", "KB", UnitTypeStorage) -> 10240, nil
- ConvertUnit(1, "h", "m", UnitTypeTime) -> 60, nil
- ConvertUnit(8, "b", "byte", UnitTypeData) -> 1, nil
func CopyStruct ¶
func CopyStruct(src, dst interface{})
CopyStruct 复制结构体,将 src 的值复制到 dst
用法:CopyStruct(&src, &dst)
注意:src、dst 必须是一个指针
func DownloadFile ¶ added in v0.13.5
DownloadFile 下载文件 参数:
- url: 文件URL
- filepath: 保存路径
返回值:
- error: 下载错误
func ExtractDomain ¶ added in v0.13.5
ExtractDomain 提取域名 参数:
- urlStr: URL字符串
返回值:
- string: 域名
- error: 提取错误
func ExtractHeaders ¶ added in v0.13.5
ExtractHeaders 提取HTTP头信息并转换为map[string]string格式 该方法将http.Header中的每个键值对转换为字符串,多个值用逗号分隔
参数:
header - HTTP请求头
返回值:
map[string]string - 转换后的头信息
func ExtractQueryParams ¶ added in v0.13.5
ExtractQueryParams 提取查询参数 参数:
- urlStr: URL字符串
返回值:
- map[string]string: 查询参数映射
- error: 提取错误
func FindAvailablePort ¶ added in v0.9.1
FindAvailablePort 查找可用端口 从指定端口开始,如果端口被占用则递增端口号,直到找到可用端口 未指定端口的情况下默认使用8080
func FormatHeaders ¶ added in v0.13.5
FormatHeaders 格式化HTTP头信息为可读的字符串格式 该方法将map[string]string格式的头信息转换为键值对字符串,每行一个头信息
参数:
headers - HTTP头信息
返回值:
string - 格式化后的头信息字符串
func FormatUnit ¶ added in v0.13.5
func FormatUnit(value interface{}, unitType UnitType, precision int, toUnit ...string) (string, error)
FormatUnit 格式化单位值,支持多种输入格式和输出格式
参数:
- unitType: 单位类型
- precision: 小数位数精度
- toUnit: 输出格式,可以是: -- "auto": 自动选择最合适的单位,默认值 -- 具体的单位符号(如 "MB", "s", "h" 等) -- value: 输入值,可以是: -- 数值(基础单位) -- 带单位的字符串(如 "10MB", "5.5s")
返回值:
- string: 格式化后的字符串
- error: 转换过程中的错误
示例:
- FormatUnit(10485760, UnitTypeStorage, 2, "auto") -> "10.00MB", nil
- FormatUnit(10485760, UnitTypeStorage, 2, "MB") -> "10.00MB", nil
- FormatUnit("10MB", UnitTypeStorage, 2, "auto") -> "10.00MB", nil
- FormatUnit("10MB", UnitTypeStorage, 2, "KB") -> "10240.00KB", nil
- FormatUnit(5500000000, UnitTypeTime, 1, "auto") -> "5.5s", nil
func GetAvailableUnits ¶ added in v0.13.5
GetAvailableUnits 获取指定类型的所有可用单位 GetAvailableUnits gets all available units of the specified type
参数:
- unitType: 单位类型
返回值:
- []string: 可用的单位符号列表
func GetCookie ¶ added in v0.13.5
GetCookie 获取HTTP Cookie值 参数:
- req: HTTP请求对象
- name: Cookie名称
返回值:
- string: Cookie值,如果不存在则返回空字符串
func GetFieldNameByJSONTag ¶
GetFieldNameByJSONTag 根据 JSON 标记获取结构体字段名
func GetFileExtension ¶ added in v0.13.5
GetFileExtension 获取文件扩展名 参数:
- filename: 文件名
返回值:
- string: 文件扩展名
func GetFormFile ¶ added in v0.13.5
GetFormFile 获取上传的文件 参数:
- req: HTTP请求对象
- key: 文件字段名
返回值:
- multipart.File: 文件对象
- *multipart.FileHeader: 文件头信息
- error: 获取错误
func GetFormValue ¶ added in v0.13.5
GetFormValue 获取表单值 参数:
- req: HTTP请求对象
- key: 表单键名
返回值:
- string: 表单值
func GetFullURL ¶ added in v0.13.5
GetFullURL 获取完整的URL(包括协议、主机、路径和查询参数) 参数:
- req: HTTP请求对象
返回值:
- string: 完整的URL字符串
func GetHTTP ¶ added in v0.13.5
GetHTTP 发送GET请求 参数:
- url: 请求URL
- headers: 请求头
返回值:
- *http.Response: HTTP响应
- error: 请求错误
func GetHTTPStatusText ¶ added in v0.13.5
GetHTTPStatusText 获取HTTP状态码文本描述 参数:
- code: HTTP状态码
返回值:
- string: 状态码文本描述
func GetHeader ¶ added in v0.13.5
GetHeader 获取HTTP请求头信息 参数:
- req: HTTP请求对象
- key: 头信息键名
返回值:
- string: 头信息值,如果不存在则返回空字符串
func GetHostInfo ¶
GetHostInfo 从HTTP请求中获取主机信息 该方法会检查TLS状态和X-Scheme头来确定协议,并优先使用代理头获取主机名
参数:
req - HTTP请求
返回值:
string - 完整的主机信息(协议://主机:端口)
func GetMimeType ¶ added in v0.13.5
GetMimeType 根据文件扩展名获取MIME类型 参数:
- extension: 文件扩展名
返回值:
- string: MIME类型
func GetQueryParam ¶ added in v0.13.5
GetQueryParam 获取URL查询参数 参数:
- req: HTTP请求对象
- key: 参数键名
返回值:
- string: 参数值,如果不存在则返回空字符串
func GetQueryParams ¶ added in v0.13.5
GetQueryParams 获取所有URL查询参数 参数:
- req: HTTP请求对象
返回值:
- map[string][]string: 所有查询参数
func GetRealIPFromHeaders ¶ added in v0.13.5
GetRealIPFromHeaders 从HTTP头信息中获取真实客户端IP 函数名:GetRealIPFromHeaders 参数: - headers map[string]string — 经过提取与归一化的请求头映射 返回值: - string — 解析出的真实客户端IP;当不可判定时返回空字符串 异常:不触发 panic 使用示例:
ip := GetRealIPFromHeaders(map[string]string{
"Ali-Cdn-Real-Ip": "203.0.113.1",
"X-Forwarded-For": "203.0.113.1, 198.51.100.2",
"X-Real-IP": "198.51.100.2",
})
// ip == "203.0.113.1"
func GetValidClientIP ¶ added in v0.13.5
GetValidClientIP 从IP列表中获取有效的客户端IP 该方法会优先选择公网IP,如果没有公网IP则选择私有IP,最后选择第一个有效IP
参数:
- ips: IP地址列表
返回值:
- string: 有效的客户端IP地址,如果找不到则返回空字符串
func InArray ¶
func InArray(val interface{}, array interface{}) (exists bool)
InArray 检查某个值是否存在于切片中 val 是要检查的值 array 是要检查的切片 exists 是返回的布尔值,表示 val 是否存在于 array 中
func IsAjaxRequest ¶ added in v0.13.5
IsAjaxRequest 检查是否为Ajax请求 参数:
- req: HTTP请求对象
返回值:
- bool: 如果是Ajax请求返回true,否则返回false
func IsBotUserAgent ¶ added in v0.13.5
IsBotUserAgent 检查是否为爬虫/机器人User-Agent 参数:
- userAgent: User-Agent字符串
返回值:
- bool: 如果是爬虫返回true,否则返回false
func IsFormRequest ¶ added in v0.13.5
IsFormRequest 检查是否为表单请求 参数:
- req: HTTP请求对象
返回值:
- bool: 如果是表单请求返回true,否则返回false
func IsHTTPS ¶ added in v0.13.5
IsHTTPS 检查是否为HTTPS请求 参数:
- req: HTTP请求对象
返回值:
- bool: 如果是HTTPS请求返回true,否则返回false
func IsJSONRequest ¶ added in v0.13.5
IsJSONRequest 检查是否为JSON请求 参数:
- req: HTTP请求对象
返回值:
- bool: 如果是JSON请求返回true,否则返回false
func IsMobileUserAgent ¶ added in v0.13.5
IsMobileUserAgent 检查是否为移动设备User-Agent 参数:
- userAgent: User-Agent字符串
返回值:
- bool: 如果是移动设备返回true,否则返回false
func IsURLSecure ¶ added in v0.13.5
IsURLSecure 检查URL是否安全(HTTPS) 参数:
- urlStr: URL字符串
返回值:
- bool: 如果是HTTPS返回true,否则返回false
func IsValidUnit ¶ added in v0.13.5
IsValidUnit 检查单位字符串是否有效 IsValidUnit checks if a unit string is valid
参数:
- unitStr: 单位字符串
- unitType: 单位类型
返回值:
- bool: 单位是否有效
示例:
- IsValidUnit("MB", UnitTypeStorage) -> true
- IsValidUnit("h", UnitTypeTime) -> true
- IsValidUnit("b", UnitTypeData) -> true
func MapToStruct ¶
func MapToStruct(mapData interface{}, obj interface{})
MapToStruct 通过reflect将map转换为结构体
func MatchWildcard ¶
MatchWildcard 检查字符串是否匹配给定的通配符模式
func NewHTTPClient ¶ added in v0.13.5
func NewHTTPClient(config *HTTPClientConfig) *http.Client
NewHTTPClient 创建新的HTTP客户端 参数:
- config: 客户端配置
返回值:
- *http.Client: HTTP客户端
func NormalizeURL ¶ added in v0.13.5
NormalizeURL 规范化URL 参数:
- urlStr: URL字符串
返回值:
- string: 规范化后的URL
- error: 规范化错误
func ParseChineseIDCard ¶ added in v0.8.0
func ParseChineseIDCard(idCard string) (gender string, age int, birthDay string, regionCode string, sequenceCode string, err error)
ParseChineseIDCard 解析中国大陆身份证号码,提取性别、年龄、生日、出生地等信息
func ParseMultipartForm ¶ added in v0.13.5
ParseMultipartForm 解析多部分表单数据 参数:
- req: HTTP请求对象
- maxMemory: 最大内存大小(字节)
返回值:
- error: 解析错误
func ParseQueryString ¶ added in v0.13.5
ParseQueryString 解析查询字符串 参数:
- query: 查询字符串
返回值:
- map[string]string: 解析后的参数映射
func PostFormHTTP ¶ added in v0.13.5
func PostFormHTTP(urlStr string, data map[string]string, headers map[string]string) (*http.Response, error)
PostFormHTTP 发送表单POST请求 参数:
- urlStr: 请求URL
- data: 表单数据
- headers: 请求头
返回值:
- *http.Response: HTTP响应
- error: 请求错误
func PostHTTP ¶ added in v0.13.5
PostHTTP 发送POST请求 参数:
- url: 请求URL
- body: 请求体
- headers: 请求头
返回值:
- *http.Response: HTTP响应
- error: 请求错误
func Random ¶
Random 生成随机字符
参数:
- length (必需): 随机字符长度。
- numericOnly (可选): 如果为 true,则只包含数字字符。
返回值:
- string: 生成的随机字符串。
示例:
randomString := Random(16) randomString := Random(16, true)
func ReadResponseBody ¶ added in v0.13.5
ReadResponseBody 读取HTTP响应体 参数:
- resp: HTTP响应
返回值:
- []byte: 响应体内容
- error: 读取错误
func ReadResponseBodyString ¶ added in v0.13.5
ReadResponseBodyString 读取HTTP响应体为字符串 参数:
- resp: HTTP响应
返回值:
- string: 响应体字符串
- error: 读取错误
func Redirect ¶ added in v0.13.5
Redirect 重定向到指定URL 参数:
- w: HTTP响应写入器
- req: HTTP请求对象
- url: 重定向URL
- code: 重定向状态码(默认302)
func RoundUnitValue ¶ added in v0.13.5
RoundUnitValue 对单位值进行四舍五入 RoundUnitValue rounds a unit value
参数:
- value: 原始值
- unit: 单位符号
- precision: 小数位数精度
- unitType: 单位类型
返回值:
- float64: 四舍五入后的值
- error: 转换错误
func SaveUploadedFile ¶ added in v0.13.5
func SaveUploadedFile(fileHeader *multipart.FileHeader, dst string) error
SaveUploadedFile 保存上传的文件 参数:
- fileHeader: 文件头信息
- dst: 目标文件路径
返回值:
- error: 保存错误
func SendHTTPRequest ¶ added in v0.13.5
func SendHTTPRequest(config *HTTPRequestConfig) (*http.Response, error)
SendHTTPRequest 发送HTTP请求 参数:
- config: 请求配置
返回值:
- *http.Response: HTTP响应
- error: 请求错误
func SetCacheHeaders ¶ added in v0.13.5
func SetCacheHeaders(w http.ResponseWriter, maxAge int, public bool)
SetCacheHeaders 设置缓存头 参数:
- w: HTTP响应写入器
- maxAge: 最大缓存时间(秒)
- public: 是否公开缓存
func SetContentDisposition ¶ added in v0.13.5
func SetContentDisposition(w http.ResponseWriter, filename, dispositionType string)
SetContentDisposition 设置内容处置头(用于文件下载) 参数:
- w: HTTP响应写入器
- filename: 文件名
- dispositionType: 处置类型("attachment" 或 "inline")
func SetContentType ¶ added in v0.13.5
func SetContentType(w http.ResponseWriter, contentType string)
SetContentType 设置内容类型 参数:
- w: HTTP响应写入器
- contentType: 内容类型
func SetHTMLContentType ¶ added in v0.13.5
func SetHTMLContentType(w http.ResponseWriter)
SetHTMLContentType 设置HTML内容类型 参数:
- w: HTTP响应写入器
func SetHeader ¶ added in v0.13.5
func SetHeader(w http.ResponseWriter, key, value string)
SetHeader 设置HTTP响应头 参数:
- w: HTTP响应写入器
- key: 头信息键名
- value: 头信息值
func SetJSONContentType ¶ added in v0.13.5
func SetJSONContentType(w http.ResponseWriter)
SetJSONContentType 设置JSON内容类型 参数:
- w: HTTP响应写入器
func SetNoCacheHeaders ¶ added in v0.13.5
func SetNoCacheHeaders(w http.ResponseWriter)
SetNoCacheHeaders 设置无缓存头 参数:
- w: HTTP响应写入器
func SetStatusCode ¶ added in v0.13.5
func SetStatusCode(w http.ResponseWriter, code int)
SetStatusCode 设置HTTP状态码 参数:
- w: HTTP响应写入器
- code: 状态码
func SetTextContentType ¶ added in v0.13.5
func SetTextContentType(w http.ResponseWriter)
SetTextContentType 设置文本内容类型 参数:
- w: HTTP响应写入器
func SplitAndValidateIPs ¶ added in v0.13.5
SplitAndValidateIPs 分割并验证多个IP地址 该方法会将逗号分隔的IP字符串分割成数组,并验证每个IP的有效性
参数:
- s: 包含多个IP地址的字符串,用逗号分隔
返回值:
- []string: 经过验证的有效IP地址列表
func SplitIPs ¶ added in v0.13.5
SplitIPs 分割多个IP地址字符串 该方法会将逗号分隔的IP字符串分割成数组
参数:
- s: 包含多个IP地址的字符串,用逗号分隔
返回值:
- []string: 分割后的IP地址列表
func StrReplace ¶
func StrReplace(search interface{}, replace interface{}, subject interface{}, count int) (interface{}, error)
StrReplace 类似于php中的str_replace
func StringStartWith ¶
StringStartWith 判断字符串是否以某个字符串开头
func StructMerge ¶
func StructMerge(dst interface{}, src ...interface{}) error
StructMerge 函数将多个源结构体中的非零值合并到目标结构体中。 源结构体按照传入顺序反向合并,后面的源结构体会覆盖前面的。 目标结构体 (dst) 必须是指向结构体的指针,所有源结构体 (src) 必须是与目标结构体类型相同的指针。
参数:
- dst: 一个指向目标结构体的指针,非零值将合并到该结构体中。
- src: 一个变参,包含多个指向源结构体的指针,非零值将从这些源结构体中提取。
返回值:
- error: 如果 dst 不是指向结构体的指针,或任何 src 元素不是与 dst 类型相同的结构体指针,则返回错误。
func StructToMap ¶
StructToMap 通过reflect将结构体转换为map
func TraceCaller ¶ added in v0.8.0
func TraceCaller()
TraceCaller 打印当前函数及其调用者的信息。
该函数会获取当前执行的函数名称和调用该函数的位置(文件和行号)。 如果无法获取当前函数或调用者的信息,将会打印错误信息并返回。
注意: - `runtime.Caller(1)` 获取的是TraceCaller的调用者信息。 - `runtime.Caller(2)` 获取的是TraceCaller的调用者的调用者信息,即调用链的上一层。
输出格式为: Function: <当前函数名称> was called from <调用者函数名称>, file: <调用者文件路径>, line: <调用者行号>
func URLDecode ¶ added in v0.13.5
URLDecode 对URL编码的字符串进行解码 参数:
- s: URL编码的字符串
返回值:
- string: 解码后的字符串
- error: 解码错误
func ValidateURL ¶ added in v0.13.5
ValidateURL 验证URL格式 参数:
- urlStr: URL字符串
返回值:
- bool: 如果是有效URL返回true,否则返回false
func WriteHTML ¶ added in v0.13.5
func WriteHTML(w http.ResponseWriter, html string) (int, error)
WriteHTML 写入HTML响应 参数:
- w: HTTP响应写入器
- html: 要写入的HTML内容
返回值:
- int: 写入的字节数
- error: 写入错误
func WriteHTMLWithStatus ¶ added in v0.13.5
WriteHTMLWithStatus 写入HTML响应并设置状态码 参数:
- w: HTTP响应写入器
- code: 状态码
- html: 要写入的HTML内容
返回值:
- int: 写入的字节数
- error: 写入错误
func WriteJSON ¶ added in v0.13.5
func WriteJSON(w http.ResponseWriter, data interface{}) error
WriteJSON 写入JSON响应 参数:
- w: HTTP响应写入器
- data: 要写入的数据
返回值:
- error: 写入错误
func WriteJSONWithStatus ¶ added in v0.13.5
func WriteJSONWithStatus(w http.ResponseWriter, code int, data interface{}) error
WriteJSONWithStatus 写入JSON响应并设置状态码 参数:
- w: HTTP响应写入器
- code: 状态码
- data: 要写入的数据
返回值:
- error: 写入错误
func WriteString ¶ added in v0.13.5
func WriteString(w http.ResponseWriter, s string) (int, error)
WriteString 写入字符串响应 参数:
- w: HTTP响应写入器
- s: 要写入的字符串
返回值:
- int: 写入的字节数
- error: 写入错误
func WriteStringWithStatus ¶ added in v0.13.5
WriteStringWithStatus 写入字符串响应并设置状态码 参数:
- w: HTTP响应写入器
- code: 状态码
- s: 要写入的字符串
返回值:
- int: 写入的字节数
- error: 写入错误
Types ¶
type Convert ¶
type Convert struct {
Value interface{}
}
func (Convert) ToDuration ¶ added in v0.13.5
ToDuration 将变量转为time.Duration类型 支持从字符串、整数、浮点数等类型转换
func (Convert) ToInterface ¶ added in v0.13.5
func (c Convert) ToInterface() interface{}
ToInterface 将变量转为interface{}类型,主要用于类型断言前的准备 此方法主要用于保持类型一致性,实际返回原始值
func (Convert) ToMapString ¶ added in v0.13.7
ToMapString 将变量转为map[string]string类型 支持从JSON字符串、结构体、map等类型转换,所有值都会被转换为字符串
func (Convert) ToReflectValue ¶ added in v0.13.8
ToReflectValue 将任意值按目标反射类型转换为可赋值的 reflect.Value 函数名:ToReflectValue 参数: - t reflect.Type — 目标类型(切片元素类型、映射值类型等) - 使用接收者 c.Value 作为原始输入值,可能是字符串、数字、布尔或时间 返回值: - reflect.Value — 转换后可赋值的值(与 t 匹配) - bool — 当发生类型不支持或位宽溢出时返回 false 异常:不触发panic 说明: - 支持 string/bool/int*/uint*/float*/time.Duration/time.Time 的转换 - 对整型/无符号/浮点类型做溢出检查,保证赋值安全
func (Convert) ToSlice ¶ added in v0.13.5
func (c Convert) ToSlice() []interface{}
ToSlice 将变量转为[]interface{}类型 支持从数组、切片、JSON字符串等类型转换
type File ¶
func (*File) CopyFileAttr ¶
CopyFileAttr 复制文件属性到目标文件
func (*File) CreateFile ¶
CreateFile 创建文件,可设置文件权限,可设置是否覆盖
func (*File) JsonToData ¶
JsonToData 将文件中的json数据解析到data中
type HTTPClientConfig ¶ added in v0.13.5
type HTTPClientConfig struct {
Timeout time.Duration
ProxyURL string
UserAgent string
SkipVerify bool
}
HTTPClientConfig HTTP客户端配置
type HTTPRequestConfig ¶ added in v0.13.5
type HTTPRequestConfig struct {
Method string
URL string
Headers map[string]string
Body []byte
Timeout time.Duration
}
HTTPRequestConfig HTTP请求配置
type IP ¶ added in v0.13.5
type IP struct {
IP string
}
IP 提供IP地址处理相关的工具函数
func (*IP) IsAllowed ¶ added in v0.13.5
IsAllowed 检查IP是否被允许(基于白名单和黑名单) 参数:
- whitelist: IP白名单列表,如果提供则只允许白名单内的IP
- blacklist: IP黑名单列表,如果提供则拒绝黑名单内的IP
返回值:
- bool: 如果IP被允许返回true,否则返回false
func (*IP) IsInCIDR ¶ added in v0.13.5
IsInCIDR 检查IP是否在CIDR范围内 参数:
- cidr: CIDR表示法(如 "192.168.1.0/24" 或 "2001:db8::/32")
返回值:
- bool: 如果IP在CIDR范围内返回true,否则返回false
func (*IP) IsLoopback ¶ added in v0.13.5
IsLoopback 检查是否为本地回环地址 参数:
- 无
返回值:
- bool: 如果是回环地址返回true,否则返回false
type JsonHelper ¶
type JsonHelper struct {
Struct interface{} // 结构体
String string // JSON字符串
Map map[string]interface{} // Map
// contains filtered or unexported fields
}
func JsonMap
deprecated
func JsonMap(jsonMap map[string]interface{}) *JsonHelper
Deprecated: 使用 Json 代替
func JsonString
deprecated
func JsonString(jsonString string) *JsonHelper
Deprecated: 使用 Json 代替
func JsonStruct
deprecated
func JsonStruct(jsonStruct interface{}) *JsonHelper
Deprecated: 使用 Json 代替
func (*JsonHelper) MakeFile ¶
func (jh *JsonHelper) MakeFile(filepath string) *JsonHelper
MakeFile 设置是否生成JSON文件及其路径
func (*JsonHelper) ToMap ¶
func (jh *JsonHelper) ToMap(newMap *map[string]interface{}) *JsonHelper
ToMap 将JSON字符串或结构体转换为Map
func (*JsonHelper) ToString ¶
func (jh *JsonHelper) ToString(newStr *string) *JsonHelper
ToString 将结构体或Map转换为JSON字符串
func (*JsonHelper) ToStruct ¶
func (jh *JsonHelper) ToStruct(newStruct interface{}) *JsonHelper
ToStruct 将JSON数据转换为结构体
type MapHelper ¶
func (*MapHelper) ArrayValues ¶
func (d *MapHelper) ArrayValues() []interface{}
func (*MapHelper) Extract ¶ added in v0.13.5
Extract 从多级map中提取任意类型的字段值 - path: 字段路径,使用点号分隔,如 "data.member_data.age" - defaultVal: 默认值,当路径不存在或类型不匹配时返回该默认值 返回:提取到的原始值,如果路径不存在返回nil
func (*MapHelper) ExtractBool ¶ added in v0.13.5
ExtractBool 从多级map中提取布尔字段值 - path: 字段路径,使用点号分隔,如 "data.member_data.is_active" - defaultVal: 默认值,当路径不存在或类型不匹配时返回该默认值 返回:提取到的布尔值,如果路径不存在或类型不匹配返回false
func (*MapHelper) ExtractFloat64 ¶ added in v0.13.5
ExtractFloat64 从多级map中提取浮点数字段值 - path: 字段路径,使用点号分隔,如 "data.member_data.salary" - defaultVal: 默认值,当路径不存在或类型不匹配时返回该默认值 返回:提取到的浮点数值,如果路径不存在或类型不匹配返回0.0
func (*MapHelper) ExtractInt ¶ added in v0.13.5
ExtractInt 从多级map中提取整数字段值 - path: 字段路径,使用点号分隔,如 "data.member_data.age" - defaultVal: 默认值,当路径不存在或类型不匹配时返回该默认值 返回:提取到的整数值,如果路径不存在或类型不匹配返回0
func (*MapHelper) ExtractInt64 ¶ added in v0.13.5
ExtractInt64 从多级map中提取64位整数字段值 - path: 字段路径,使用点号分隔,如 "data.member_data.big_id" - defaultVal: 默认值,当路径不存在或类型不匹配时返回该默认值 返回:提取到的64位整数值,如果路径不存在或类型不匹配返回0
func (*MapHelper) ExtractString ¶ added in v0.13.5
ExtractString 从多级map中提取字符串字段值 - path: 字段路径,使用点号分隔,如 "data.member_data.gender_text" - defaultVal: 默认值,当路径不存在或类型不匹配时返回该默认值 返回:提取到的字符串值,如果路径不存在或类型不匹配返回空字符串
func (*MapHelper) ExtractStringSlice ¶ added in v0.13.5
ExtractStringSlice 从多级map中提取字符串切片字段值 - path: 字段路径,使用点号分隔,如 "data.member_data.tags" - defaultVal: 默认值,当路径不存在或类型不匹配时返回该默认值 返回:提取到的字符串切片,如果路径不存在或类型不匹配返回空切片
func (*MapHelper) ExtractTime ¶ added in v0.13.5
ExtractTime 从多级map中提取时间字段值 - path: 字段路径,使用点号分隔,如 "data.member_data.created_at" - defaultVal: 默认值,当路径不存在或类型不匹配时返回该默认值 返回:提取到的时间值,如果路径不存在或类型不匹配返回零值时间
type MoneyHelper ¶
type MoneyHelper struct {
Amount int64 `json:"amount" default:"0"` // 单位为厘,1000为1元
// contains filtered or unexported fields
}
func Money ¶
func Money(input interface{}) *MoneyHelper
func (*MoneyHelper) FloatString ¶
func (m *MoneyHelper) FloatString(parts ...string) string
FloatString 输出字符串金额,接受前缀和后缀 参数:
parts - 可变参数列表,第一个参数表示前缀,第二个参数表示后缀,如果省略则不添加
func (*MoneyHelper) GreaterThan ¶
func (m *MoneyHelper) GreaterThan(other *MoneyHelper) bool
GreaterThan 比较大小
func (*MoneyHelper) LessThan ¶
func (m *MoneyHelper) LessThan(other *MoneyHelper) bool
LessThan 比较大小
func (*MoneyHelper) Multiply ¶
func (m *MoneyHelper) Multiply(factor float64) *MoneyHelper
Multiply 乘法操作
func (*MoneyHelper) SetAmount ¶
func (m *MoneyHelper) SetAmount(value interface{}) *MoneyHelper
SetAmount 设置金额,接受不同格式的输入
func (*MoneyHelper) Subtract ¶
func (m *MoneyHelper) Subtract(other *MoneyHelper) *MoneyHelper
Subtract 减法操作
type Str ¶
type Str struct {
String string
Float64 float64
Float32 float32
Int64 int64
Int32 int32
Int16 int16
Int8 int8
Int int
Uint64 uint64
Uint32 uint32
Uint16 uint16
Uint8 uint8
Uint uint
}
func (*Str) Base64UrlDecode ¶
Base64UrlDecode 解码 URL 和文件名安全的 Base64 编码字符串
func (*Str) Base64UrlEncode ¶
Base64UrlEncode 对字符串进行 URL 和文件名安全的 Base64 编码
func (*Str) ByteSubstr ¶
ByteSubstr 返回从 start 开始、长度为 length 的子字符串
func (*Str) ConvertBetweenUnits ¶ added in v0.13.5
func (s *Str) ConvertBetweenUnits(value float64, fromUnit, toUnit string, unitType UnitType) (*Str, error)
ConvertBetweenUnits 在不同单位之间转换数值并返回新的Str对象
参数:
- value: 原始数值
- fromUnit: 原始单位符号
- toUnit: 目标单位符号
- unitType: 单位类型
返回值:
- *Str: 包含转换后数值的Str对象
- error: 转换过程中的错误
示例:
- s := NewStr(""); s.ConvertBetweenUnits(10, "MB", "KB", UnitTypeStorage) -> NewStr("10240"), nil
func (*Str) ConvertCamelToSnake ¶
ConvertCamelToSnake 转换驼峰字符串为下划线字符串
func (*Str) EscapeHTML ¶
EscapeHTML escapes HTML characters in the value to prevent XSS
func (*Str) FormatAsUnit ¶ added in v0.13.5
FormatAsUnit 将数值格式化为带单位的字符串
参数:
- value: 数值(以基础单位表示)
- unitType: 单位类型
- precision: 小数位数精度
- toUnit: 输出格式("auto"自动选择单位或具体单位符号)
返回值:
- *Str: 新的Str实例,包含格式化后的字符串
示例:
- s := NewStr(""); s.FormatAsUnit(10485760, UnitTypeStorage, 2, "auto") -> "10.00MB"
- s := NewStr(""); s.FormatAsUnit(10485760, UnitTypeStorage, 0, "KB") -> "10240KB"
func (*Str) GetUnitTypeFromString ¶ added in v0.13.5
GetUnitTypeFromString 获取字符串中单位的类型
参数:
- unitType: 单位类型
返回值:
- UnitType: 单位类型
- error: 解析错误
示例:
- s := NewStr("10MB"); s.GetUnitTypeFromString(UnitTypeStorage) -> UnitTypeStorage, nil
func (*Str) IsUnitString ¶ added in v0.13.5
IsUnitString 检查字符串是否为有效的单位字符串
参数:
- unitType: 单位类型
返回值:
- bool: 是否为有效的单位字符串
示例:
- s := NewStr("MB"); s.IsUnitString(UnitTypeStorage) -> true
- s := NewStr("invalid"); s.IsUnitString(UnitTypeStorage) -> false
func (*Str) ParseUnit ¶ added in v0.13.5
ParseUnit 解析字符串中的单位信息 ParseUnit parses unit information from string
参数:
- unitType: 单位类型
返回值:
- float64: 解析出的数值(以基础单位表示)
- *Unit: 单位信息
- error: 解析过程中的错误
示例:
- s := NewStr("10MB"); s.ParseUnit(UnitTypeStorage) -> 10485760, &Unit{...}, nil
- s := NewStr("1h"); s.ParseUnit(UnitTypeTime) -> 3600000000000, &Unit{...}, nil
- s := NewStr("8b"); s.ParseUnit(UnitTypeData) -> 1, &Unit{...}, nil
func (*Str) StartsWith ¶
StartsWith 检查字符串是否以指定的子字符串开头
func (*Str) ToUnitValue ¶ added in v0.13.5
ToUnitValue 将字符串转换为基础单位的数值
参数:
- unitType: 单位类型
返回值:
- float64: 转换后的数值(以基础单位表示)
- error: 转换过程中的错误
示例:
- s := NewStr("10MB"); s.ToUnitValue(UnitTypeStorage) -> 10485760, nil
func (*Str) Trim ¶
Trim returns a slice of the string s with all leading and trailing Unicode code points contained in cutSet removed.
type Unit ¶ added in v0.13.5
type Unit struct {
Name string // 单位名称
Symbols []string // 单位符号(支持多种表示方式)
Factor float64 // 转换因子(相对于基础单位)
UnitType UnitType // 单位类型
}
Unit 定义单位结构 Unit defines the unit structure
func ParseUnitString ¶ added in v0.13.5
ParseUnitString 解析包含单位的字符串,返回数值和单位信息 ParseUnitString parses a string containing units and returns the numeric value and unit information
参数:
- str: 包含单位的字符串,如 "10MB", "5.5s", "1.2KB"
- unitType: 单位类型
返回值:
- float64: 转换后的数值(以基础单位表示)
- *Unit: 解析出的单位信息
- error: 解析过程中的错误
示例:
- ParseUnitString("10MB", UnitTypeStorage) -> 10485760, Unit{Name: "Megabyte", ...}, nil
- ParseUnitString("5.5s", UnitTypeTime) -> 5500000000, Unit{Name: "Second", ...}, nil
- ParseUnitString("8byte", UnitTypeData) -> 64, Unit{Name: "Byte", ...}, nil
type UnitType ¶ added in v0.13.5
type UnitType int
UnitType 定义单位类型 UnitType defines the type of unit
func GetUnitType ¶ added in v0.13.5
GetUnitType 获取单位的类型 GetUnitType gets the type of a unit
参数:
- unitStr: 单位字符串
- unitType: 单位类型
返回值:
- UnitType: 单位类型
- error: 解析错误
示例:
- GetUnitType("MB", UnitTypeStorage) -> UnitTypeStorage, nil
- GetUnitType("h", UnitTypeTime) -> UnitTypeTime, nil
- GetUnitType("b", UnitTypeData) -> UnitTypeData, nil