Documentation
¶
Overview ¶
Example (LogrusLoggerAdapter) ¶
Example_logrusLoggerAdapter 演示如何使用 logrus 日志库适配器 Example_logrusLoggerAdapter demonstrates how to use logrus logger adapter
package main
import (
"context"
"fmt"
utils "github.com/Is999/go-utils"
)
// logrusLoggerAdapter 将 logrus Logger 适配到 utils.Logger 接口
// logrusLoggerAdapter adapts logrus Logger to utils.Logger interface
//
// 使用示例 / Usage example:
// import "github.com/sirupsen/logrus"
//
// logrusLogger := logrus.New()
// adapter := &logrusLoggerAdapter{logger: logrusLogger}
// utils.Configure(utils.WithLogger(adapter))
type logrusLoggerAdapter struct {
logger interface{}
}
func (l *logrusLoggerAdapter) Debug(msg string, args ...any) {
fmt.Printf("[LOGRUS DEBUG] %s %v\n", msg, args)
}
func (l *logrusLoggerAdapter) Info(msg string, args ...any) {
fmt.Printf("[LOGRUS INFO] %s %v\n", msg, args)
}
func (l *logrusLoggerAdapter) Warn(msg string, args ...any) {
fmt.Printf("[LOGRUS WARN] %s %v\n", msg, args)
}
func (l *logrusLoggerAdapter) Error(msg string, args ...any) {
fmt.Printf("[LOGRUS ERROR] %s %v\n", msg, args)
}
func (l *logrusLoggerAdapter) With(args ...any) utils.Logger {
return &logrusLoggerAdapter{logger: l.logger}
}
func (l *logrusLoggerAdapter) Enabled(ctx context.Context, level utils.LogLevel) bool {
return true
}
func main() {
// 创建适配器实例
logrusAdapter := &logrusLoggerAdapter{}
// 直接使用适配器(因为 Configure 只能调用一次)
// Use adapter directly (since Configure can only be called once)
logrusAdapter.Info("Application started", "version", "2.0.0")
logrusAdapter.Warn("Warning message")
}
Output: [LOGRUS INFO] Application started [version 2.0.0] [LOGRUS WARN] Warning message []
Example (ZapLoggerAdapter) ¶
Example_zapLoggerAdapter 演示如何使用 zap 日志库适配器 Example_zapLoggerAdapter demonstrates how to use zap logger adapter
package main
import (
"context"
"fmt"
utils "github.com/Is999/go-utils"
)
// zapLoggerAdapter 将 zap Logger 适配到 utils.Logger 接口
// zapLoggerAdapter adapts zap Logger to utils.Logger interface
//
// 使用示例 / Usage example:
// import "go.uber.org/zap"
//
// zapLogger, _ := zap.NewProduction()
// adapter := &zapLoggerAdapter{logger: zapLogger.Sugar()}
// utils.Configure(utils.WithLogger(adapter))
type zapLoggerAdapter struct {
logger interface{}
}
func (z *zapLoggerAdapter) Debug(msg string, args ...any) {
fmt.Printf("[ZAP DEBUG] %s %v\n", msg, args)
}
func (z *zapLoggerAdapter) Info(msg string, args ...any) {
fmt.Printf("[ZAP INFO] %s %v\n", msg, args)
}
func (z *zapLoggerAdapter) Warn(msg string, args ...any) {
fmt.Printf("[ZAP WARN] %s %v\n", msg, args)
}
func (z *zapLoggerAdapter) Error(msg string, args ...any) {
fmt.Printf("[ZAP ERROR] %s %v\n", msg, args)
}
func (z *zapLoggerAdapter) With(args ...any) utils.Logger {
return &zapLoggerAdapter{logger: z.logger}
}
func (z *zapLoggerAdapter) Enabled(ctx context.Context, level utils.LogLevel) bool {
return true
}
func main() {
// 创建适配器实例
zapAdapter := &zapLoggerAdapter{}
// 直接使用适配器进行日志输出(演示目的)
// Use adapter directly for logging output (demonstration purpose)
zapAdapter.Info("Application started", "version", "1.0.0")
zapAdapter.Debug("Debug information", "key", "value")
// 使用 With 添加上下文字段(注意:此演示实现不保留上下文)
// Use With to add context fields (note: this demo implementation doesn't retain context)
childLogger := zapAdapter.With("request_id", "12345")
childLogger.Info("Processing request")
}
Output: [ZAP INFO] Application started [version 1.0.0] [ZAP DEBUG] Debug information [key value] [ZAP INFO] Processing request []
Index ¶
- Constants
- Variables
- func Account(value string, min, max uint8) error
- func AddFileToTar(tarWriter *tar.Writer, fileToCompress string, baseDir string) error
- func AddFileToZip(zipWriter *zip.Writer, fileToCompress string, baseDir string) error
- func AddPEMHeaders(key, keyType string) (string, error)
- func AddTime(t time.Time, addTimes ...string) (time.Time, error)
- func After(layout string, t1, t2 string) (bool, error)
- func Alnum(value string) bool
- func Alpha(value string) bool
- func Amount(amount string, decimal uint8, signed ...bool) bool
- func Before(layout string, t1, t2 string) (bool, error)
- func BinDec(str string) (int64, error)
- func BinHex(str string) (string, error)
- func BinOct(str string) (string, error)
- func CST() *time.Location
- func Certificate(config *tls.Config, certFile, keyFile string) error
- func CheckDate(year, month, day int) bool
- func ClientIP(r *http.Request) string
- func Configure(opts ...Option)
- func Copy(src, dst string) error
- func Date(timeZone *time.Location, layout string, timestamp ...int64) string
- func DateInfo(t time.Time) map[string]interface{}
- func DecBin(number int64) string
- func DecHex(number int64) string
- func DecOct(number int64) string
- func Diff[T Ordered](s1, s2 []T) []T
- func Domain(value string) bool
- func DrainBody(b io.ReadCloser) ([]byte, io.ReadCloser, error)
- func Email(value string) bool
- func Empty(value string) bool
- func Equal(layout string, t1, t2 string) (bool, error)
- func FileType(f *os.File) (string, error)
- func GenerateKeyRSA(path string, bits int, pkcs ...bool) ([]string, error)
- func GetEnv(key string, defaultVal ...string) string
- func GetFunctionName(i interface{}) string
- func HasCount[T Ordered](v T, s []T) (count int)
- func HasSymbols(value string) bool
- func HexBin(data string) (string, error)
- func HexDec(str string) (int64, error)
- func HexOct(str string) (string, error)
- func Intersect[T Ordered](s1, s2 []T) []T
- func IsDir(path string) bool
- func IsExist(path string) bool
- func IsFile(filepath string) bool
- func IsHas[T Ordered](v T, s []T) bool
- func Line(r io.Reader, handle ReadLine) error
- func Local() *time.Location
- func LocalIP() string
- func MapDiff[K, V Ordered](m1, m2 map[K]V) []V
- func MapDiffKey[K Ordered, V any](m1, m2 map[K]V) []K
- func MapFilter[K Ordered, V any](m map[K]V, f func(key K, value V) bool) map[K]V
- func MapIntersect[K, V Ordered](m1, m2 map[K]V) []V
- func MapIntersectKey[K Ordered, V any](m1, m2 map[K]V) []K
- func MapKeys[K Ordered, V any](m map[K]V) []K
- func MapRange[K Ordered, V any](m map[K]V, f func(key K, value V) bool, isReverse ...bool)
- func MapValues[K Ordered, V any](m map[K]V, isReverse ...bool) []V
- func Marshal(v any) ([]byte, error)
- func Md5(str string) string
- func MixStr(value string) bool
- func Mobile(value string) bool
- func MonthDay(year int, month int) (days int)
- func NumberFormat(number float64, decimals uint, decPoint, thousandsSep string) string
- func Numeric(value string) bool
- func OctBin(data string) (string, error)
- func OctDec(str string) (int64, error)
- func OctHex(data string) (string, error)
- func PassWord(value string, min, max uint8) error
- func PassWord2(value string, min, max uint8) error
- func PassWord3(value string, min, max uint8) error
- func Phone(value string) bool
- func Pkcs7Padding(data []byte, blockSize int) []byte
- func Pkcs7UnPadding(data []byte) ([]byte, error)
- func ProxyURL(transport *http.Transport, proxyURL string) error
- func QQ(value string) bool
- func Rand(minInt, maxInt int64, r ...*rand.Rand) int64
- func RandStr(n int, r ...*rand.Rand) string
- func RandStr2(n int, r ...*rand.Rand) string
- func RandStr3(n int, alpha string, r ...*rand.Rand) string
- func Read(r io.Reader, handle ReadBlock) error
- func Redirect(w http.ResponseWriter, url string, opts ...ResponseOption)
- func RemovePEMHeaders(pem string) string
- func Replace(s string, oldnew map[string]string) string
- func Retry(maxRetries uint8, fn func(tries int) error) error
- func Reverse[T Ordered](s []T) []T
- func RootCAs(config *tls.Config, rootCAs string) error
- func Round(num float64, precision int) float64
- func Scan(r io.Reader, handle ReadScan, size ...int) error
- func ServerIP() string
- func Sha1(str string) string
- func Sha256(str string) string
- func Sha512(str string) string
- func Size(filepath string) (int64, error)
- func SizeFormat(size int64, decimals uint) string
- func Str2Float(s string) (i float64)
- func Str2Int(s string) (i int)
- func Str2Int64(s string) (i int64)
- func StrRev(str string) string
- func Strtotime(timeZone *time.Location, parse ...string) (t time.Time, err error)
- func Sub(layout string, t1, t2 string) (time.Duration, error)
- func Substr(str string, start, length int) string
- func SumMap[K Ordered, V Number](m map[K]V) V
- func SumSlice[T Number](nums []T) T
- func Tar(tarFile string, files []string) error
- func TarGz(tarGzFile string, files []string) error
- func Ternary[T any](expr bool, trueVal, falseVal T) T
- func TimeDay(value string) bool
- func TimeFormat(timeZone *time.Location, layout string, timestamp ...int64) string
- func TimeMonth(value string) bool
- func TimeParse(timeZone *time.Location, layout, timeStr string) (time.Time, error)
- func Timestamp(value string) bool
- func UTC() *time.Location
- func UnIntZero(value string) bool
- func UnInteger(value string) bool
- func UnNumeric(value string) bool
- func UnTar(tarFile, destDir string) error
- func UnZip(zipFile, destDir string) error
- func UniqId(l uint8, r ...*rand.Rand) string
- func Unique[T Ordered](s []T) []T
- func Unmarshal(data []byte, v any) error
- func UrlPath(urlPath string, params url.Values) (string, error)
- func ZeroPadding(data []byte, blockSize int) []byte
- func ZeroUnPadding(data []byte) ([]byte, error)
- func Zh(value string) bool
- func Zip(zipFile string, files []string) error
- type Body
- type Cipher
- func (c *Cipher) Decrypt(encrypt string, mode McryptMode, decode DecodeString, unPadding UnPadding) (string, error)
- func (c *Cipher) DecryptCBC(data []byte, unPadding UnPadding) ([]byte, error)
- func (c *Cipher) DecryptCFB(data []byte, unPadding UnPadding) ([]byte, error)
- func (c *Cipher) DecryptCTR(data []byte, unPadding UnPadding) ([]byte, error)
- func (c *Cipher) DecryptECB(data []byte, unPadding UnPadding) ([]byte, error)
- func (c *Cipher) DecryptOFB(data []byte, unPadding UnPadding) ([]byte, error)
- func (c *Cipher) Encrypt(data string, mode McryptMode, encode EncodeToString, padding Padding) (string, error)
- func (c *Cipher) EncryptCBC(data []byte, padding Padding) ([]byte, error)
- func (c *Cipher) EncryptCFB(data []byte, padding Padding) ([]byte, error)
- func (c *Cipher) EncryptCTR(data []byte, padding Padding) ([]byte, error)
- func (c *Cipher) EncryptECB(data []byte, padding Padding) ([]byte, error)
- func (c *Cipher) EncryptOFB(data []byte, padding Padding) ([]byte, error)
- type CipherBlock
- type CipherOption
- type Curl
- func (c *Curl) AddCookies(cookies ...*http.Cookie) *Curl
- func (c *Curl) AddHeader(key string, values ...string) *Curl
- func (c *Curl) AddHeaders(headers map[string][]string) *Curl
- func (c *Curl) AddParam(key string, values ...string) *Curl
- func (c *Curl) AddParams(params map[string][]string) *Curl
- func (c *Curl) AfterBody(f func(body []byte) error) *Curl
- func (c *Curl) AfterDone(f func(client *http.Client, request *http.Request, response *http.Response)) *Curl
- func (c *Curl) AfterResponse(f func(response *http.Response) (isDone bool, err error)) *Curl
- func (c *Curl) BeforeClient(f func(request *http.Client) error) *Curl
- func (c *Curl) BeforeRequest(f func(request *http.Request) error) *Curl
- func (c *Curl) ClearCookies() *Curl
- func (c *Curl) CloseIdleConnections()
- func (c *Curl) DelCookies(cookieName ...string) *Curl
- func (c *Curl) DelHeaders(keys ...string) *Curl
- func (c *Curl) DelParams(keys ...string) *Curl
- func (c *Curl) Delete(url string) (err error)
- func (c *Curl) Get(url string) (err error)
- func (c *Curl) GetCookie(cookieName string) *http.Cookie
- func (c *Curl) GetHeader() http.Header
- func (c *Curl) GetHeaderValues(key string) []string
- func (c *Curl) GetParamValues(key string) []string
- func (c *Curl) GetParams() url.Values
- func (c *Curl) GetRequestId() string
- func (c *Curl) HasCookie(cookieName string) bool
- func (c *Curl) HasHeader(key string) bool
- func (c *Curl) HasParam(key string) bool
- func (c *Curl) Head(url string) error
- func (c *Curl) InsecureSkipVerify(isSkip bool) *Curl
- func (c *Curl) Options(url string) (err error)
- func (c *Curl) Patch(url string) (err error)
- func (c *Curl) Post(url string) (err error)
- func (c *Curl) PostForm(url string) error
- func (c *Curl) Put(url string) (err error)
- func (c *Curl) ReSetHeader(header http.Header) *Curl
- func (c *Curl) ReSetParams(params url.Values) *Curl
- func (c *Curl) Send(method, url string, body io.Reader) (err error)
- func (c *Curl) SetBasicAuth(username, password string) *Curl
- func (c *Curl) SetBody(body io.Reader) *Curl
- func (c *Curl) SetBodyBytes(body []byte) *Curl
- func (c *Curl) SetCertKey(cert, key string) *Curl
- func (c *Curl) SetContentType(contentType string) *Curl
- func (c *Curl) SetCookies(cookies ...*http.Cookie) *Curl
- func (c *Curl) SetDefLogOutput(enable bool) *Curl
- func (c *Curl) SetDump(dump bool) *Curl
- func (c *Curl) SetHeader(key, value string) *Curl
- func (c *Curl) SetHeaders(headers map[string]string) *Curl
- func (c *Curl) SetMaxRetry(max uint8) *Curl
- func (c *Curl) SetParam(key, value string) *Curl
- func (c *Curl) SetParams(params map[string]string) *Curl
- func (c *Curl) SetProxyURL(proxyURL string) *Curl
- func (c *Curl) SetRequestId(requestId ...string) *Curl
- func (c *Curl) SetRootCAs(rootCAs string) *Curl
- func (c *Curl) SetStatusCode(statusCode ...int) *Curl
- func (c *Curl) SetTimeout(timeout uint16) *Curl
- func (c *Curl) SetUserAgent(userAgent string) *Curl
- type CurlOption
- func WithCurlBasicAuth(username, password string) CurlOption
- func WithCurlBody(body io.Reader) CurlOption
- func WithCurlBodyBytes(body []byte) CurlOption
- func WithCurlCertKey(cert, key string) CurlOption
- func WithCurlContentType(contentType string) CurlOption
- func WithCurlCookies(cookies ...*http.Cookie) CurlOption
- func WithCurlDefLogOutput(enable bool) CurlOption
- func WithCurlDump(dump bool) CurlOption
- func WithCurlDumpBodyLimit(limit int64) CurlOption
- func WithCurlHeader(key, value string) CurlOption
- func WithCurlHeaders(headers map[string]string) CurlOption
- func WithCurlInsecureSkipVerify(isSkip bool) CurlOption
- func WithCurlLogger(logger Logger) CurlOption
- func WithCurlMaxRetry(max uint8) CurlOption
- func WithCurlParams(params map[string]string) CurlOption
- func WithCurlProxyURL(proxyURL string) CurlOption
- func WithCurlRequestId(requestId string) CurlOption
- func WithCurlRootCAs(rootCAs string) CurlOption
- func WithCurlStatusCode(statusCode ...int) CurlOption
- func WithCurlTimeout(timeout time.Duration) CurlOption
- type Decode
- type DecodeString
- type Encode
- type EncodeToString
- type FileInfo
- type Float
- type Form
- func (f *Form) AddFile(fileName string, filePath ...string) *Form
- func (f *Form) AddFiles(files map[string][]string) *Form
- func (f *Form) AddParam(key string, values ...string) *Form
- func (f *Form) AddParams(params map[string][]string) *Form
- func (f *Form) DelFiles(fileNames ...string)
- func (f *Form) DelParams(keys ...string)
- func (f *Form) Reader() (body io.Reader, contentType string, err error)
- func (f *Form) SetFile(fileName, filePath string) *Form
- func (f *Form) SetFiles(files map[string]string) *Form
- func (f *Form) SetParam(key, value string) *Form
- func (f *Form) SetParams(params map[string]string) *Form
- type Frame
- type Integer
- type LogLevel
- type Logger
- type McryptMode
- type Number
- type Once
- type Option
- type Ordered
- type Padding
- type Pool
- type PoolOption
- type RSA
- func (r *RSA) Decrypt(encrypt string, decode DecodeString) (string, error)
- func (r *RSA) DecryptOAEP(encrypt string, decode DecodeString, hash hash.Hash) (string, error)
- func (r *RSA) Encrypt(data string, encode EncodeToString) (string, error)
- func (r *RSA) EncryptOAEP(data string, encode EncodeToString, hash hash.Hash) (string, error)
- func (r *RSA) IsSetPrivateKey() error
- func (r *RSA) IsSetPublicKey() error
- func (r *RSA) SetPrivateKey(privateKey string, isFilePath bool) error
- func (r *RSA) SetPublicKey(publicKey string, isFilePath bool) error
- func (r *RSA) Sign(data string, hash crypto.Hash, encode EncodeToString) (string, error)
- func (r *RSA) SignPSS(data string, hash crypto.Hash, encode EncodeToString, opts *rsa.PSSOptions) (string, error)
- func (r *RSA) Verify(data, sign string, hash crypto.Hash, decode DecodeString) error
- func (r *RSA) VerifyPSS(data, sign string, hash crypto.Hash, decode DecodeString, opts *rsa.PSSOptions) error
- type RSAOption
- type ReadBlock
- type ReadLine
- type ReadScan
- type Response
- func (r *Response) ContentType(contentType string) *Response
- func (r *Response) Download(filePath string, rename ...string)
- func (r *Response) Encode() ([]byte, error)
- func (r *Response) Fail(code int, message string, data ...any)
- func (r *Response) Header(f func(header http.Header)) *Response
- func (r *Response) Html(data string)
- func (r *Response) Show(filePath string)
- func (r *Response) StatusCode(statusCode int) *Response
- func (r *Response) Success(code int, data any, message ...string)
- func (r *Response) Text(data string)
- func (r *Response) Write(body []byte)
- func (r *Response) Xml(data any)
- type ResponseOption
- type Signed
- type Slice
- type UnPadding
- type Unsigned
- type WriteFile
- type WriteOption
Examples ¶
Constants ¶
const ( Byte int64 = 1 << (10 * iota) // 1Byte KB // 1024Byte = 1KB MB // 1048576Byte = 1024KB = 1MB GB // 1073741824Byte = 1048576KB = 1024MB = 1GB TB // 1099511627776Byte = ... PB // 1125899906842624Byte EB // 1152921504606846976Byte )
计算机存储单位:Byte、KB、MB、GB、TB、PB、EB int64最大支持EB
const ( YearTime = "2006" MonthTime = YearTime + "01" DayTime = MonthTime + "02" HourTime = DayTime + "15" MinuteTime = HourTime + "04" SecondTime = MinuteTime + "05" )
const ( // ALPHA 英文字母:A-Za-z ALPHA = `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz` // DIGIT 数字:0-9 DIGIT = `0123456789` // ALNUM 英文字母+数字:A-Za-z0-9 ALNUM = ALPHA + DIGIT )
Variables ¶
var DONE = errors.New("DONE")
DONE 完成终止
var RandSource = rand.New(rand.NewPCG(uint64(time.Now().UnixNano()), uint64(time.Now().UnixNano())))
RandSource rand
Functions ¶
func AddTime ¶ added in v1.21.4
AddTime 增加时间
addTimes 增加时间(Y年,M月,D日,H时,I分,S秒,L毫秒,C微妙,N纳秒) 示例:DateInfo(time, "-1D", "1M", "-1Y", "+4H", "20I", "30S", "76N")
func Date ¶
Date 使用 patterns 定义的格式对时间格式化
timeZone 时区 layout 格式化,例: - Date(timeZone, "Y-m-d H:i:s", unix) timestamp Unix时间戳:sec秒和nsec纳秒
func DateInfo ¶
DateInfo 获取日期信息
返回:year int - 年, month int - 月,monthEn string - 英文月, day int - 日,yearDay int - 一年中第几日, weekDay int - 一周中第几日, hour int - 时,hour int - 分,second int - 秒, millisecond int - 毫秒,microsecond int - 微妙,nanosecond int - 纳秒, unix int64 - 时间戳-秒,unixNano int64 - 时间戳-纳秒, weekDay int - 星期几,weekDayEn string - 星期几英文, yearWeek int - 一年中第几周, date string - 格式化日期,dateNs string - 格式化日期(纳秒)
func DrainBody ¶
func DrainBody(b io.ReadCloser) ([]byte, io.ReadCloser, error)
DrainBody 读取read内容并返回其内容和一个新的ReadCloser,
func GenerateKeyRSA ¶
GenerateKeyRSA 生成秘钥(公钥PKCS8格式 私钥PKCS1格式)
path 秘钥存放地址 bits 生成秘钥位大小: 512、1024、2048、4096 pkcs 秘钥格式, 默认格式(公钥PKCS8格式 私钥PKCS1格式): - pkcs[0] isPubPKCS8 公钥是否是PKCS8格式: 默认 true - pkcs[1] isPriPKCS1 私钥是否是PKCS1格式: 默认 true RETURN: - []string 返回两个文件名, 第一个公钥文件名, 第二个私钥文件名
func GetFunctionName ¶ added in v1.22.12
func GetFunctionName(i interface{}) string
GetFunctionName 获取函数名(普通函数、结构体方法或匿名函数)
func Intersect ¶ added in v1.22.0
func Intersect[T Ordered](s1, s2 []T) []T
Intersect 计算s1与s2的交集即s1中有而s2中也有的元素
func MapDiffKey ¶
MapDiffKey 计算m1与m2的键差集即m1中有但m2中没有的键
func MapIntersect ¶
func MapIntersect[K, V Ordered](m1, m2 map[K]V) []V
MapIntersect 计算m1与m2的值交集即m1与m2都有的值
func MapIntersectKey ¶
MapIntersectKey 计算m1与m2的键交集即m1与m2都有的键
func MapRange ¶
MapRange 有序遍历map元素,对map的key排序并按排序后的key遍历m
f 函数接收key与value,返回一个bool值,如果f函数返回false则终止遍历 isReverse 是否降序排列:true 降序,false 升序
func MapValues ¶
MapValues 有序获取map的所有value,对map的key排序并按排序后的key返回其value
isReverse 是否降序排列:true 降序,false 升序,未指定则不排序直接返回所有value
func NumberFormat ¶
NumberFormat 以千位分隔符方式格式化一个数字
number 要格式化的数字 decimals 保留几位小数 decPoint 小数点[.] thousandsSep 千位分隔符[,]
func Rand ¶
Rand 返回min~max之间的随机数,值可能包含min和max
minInt 最小值 maxInt 最大值 r 随机种子 rand.NewSource(time.Now().UnixNano()) : 批量生成时传入r参数可提升生成随机数效率
func RandStr ¶
RandStr 随机生成字符串,使用LETTERS规则
n 生成字符串长度 r 随机种子 rand.NewSource(time.Now().UnixNano()) : 批量生成时传入r参数可提升生成随机数效率
func RandStr2 ¶
RandStr2 随机生成字符串,使用ALPHANUM规则
n 生成字符串长度 r 随机种子 rand.NewSource(time.Now().UnixNano()) : 批量生成时传入r参数可提升生成随机数效率
func RandStr3 ¶
RandStr3 随机生成字符串
n 生成字符串长度 alpha 生成随机字符串的种子 r 随机种子 rand.NewSource(time.Now().UnixNano()) : 批量生成时传入r参数可提升生成随机数效率
func Redirect ¶
func Redirect(w http.ResponseWriter, url string, opts ...ResponseOption)
Redirect 重定向
url 重定向地址
Example ¶
serveMux.HandleFunc("/response/redirect", func(w http.ResponseWriter, r *http.Request) {
// 重定向
utils.Redirect(w, "/response/json")
})
func Strtotime ¶
Strtotime 解析时间字符串(不确定的时间格式,尽可能解析时间字符串)
timeZone 时区 parse 解析时间字符串包含两个参数: - layout 格式化样式字符串 - timeStr 时间字符串 例: - Strtotime(timeZone, "2006-01-02 15:04:05") // 当前时间 - Strtotime(timeZone, "2006-01-02 15:04:05", timeStr) // 指定时间timeStr - Strtotime(timeZone, "Y-m-d H:i:s") // 当前时间 - Strtotime(timeZone, "Y-m-d H:i:s", timeStr) // 指定时间timeStr
func Substr ¶
Substr 字符串截取
str 被截取的字符串 start 截取的起始位置,即截取的第一个字符所在的索引: - start小于0时,start = len(str) + start length 截取的截止位置,即截取的最后一个字符所在的索引: - length大于0时,length表示为截取子字符串的长度,截取的最后一个字符所在的索引值为:start + length - length小于0时,length表示为截取的最后一个字符所在的索引,值为:len(str) + length + 1 - 例如:等于-1时,表示截取到最后一个字符;等于-2时,表示截取到倒数第二个字符
func TimeFormat ¶
TimeFormat 时间戳格式化为时间字符串
timeZone 时区 layout 格式化,例: - TimeFormat(timeZone, "2006-01-02 15:04:05", unix) timestamp Unix时间戳:sec秒和nsec纳秒
func TimeParse ¶
TimeParse 解析时间字符串
timeZone 时区 layout 格式化,例: - TimeFormat(timeZone, "2006-01-02 15:04:05", timeStr) timeStr 时间字符串
Types ¶
type Cipher ¶
type Cipher struct {
// contains filtered or unexported fields
}
func NewCipher ¶
func NewCipher(key string, block CipherBlock, opts ...CipherOption) (*Cipher, error)
NewCipher Cipher
key 秘钥 block 密码: (AES | DES).NewCipher
func (*Cipher) Decrypt ¶
func (c *Cipher) Decrypt(encrypt string, mode McryptMode, decode DecodeString, unPadding UnPadding) (string, error)
Decrypt 解密
encrypt 待解密数据 mode 加密模式: - ECB: Decrypt(encrypt, ECB, decode, unPadding) - CBC: Decrypt(encrypt, CBC, decode, unPadding) - CTR: Decrypt(encrypt, CTR, decode, unPadding) - CFB: Decrypt(encrypt, CFB, decode, unPadding) - OFB: Decrypt(encrypt, OFB, decode, unPadding) decode 解码方法 unPadding 去除填充数据方法
func (*Cipher) DecryptCBC ¶
DecryptCBC 解密
func (*Cipher) DecryptCFB ¶
DecryptCFB 解密
func (*Cipher) DecryptCTR ¶
DecryptCTR 解密
func (*Cipher) DecryptECB ¶
DecryptECB 解密
func (*Cipher) DecryptOFB ¶
DecryptOFB 解密
func (*Cipher) Encrypt ¶
func (c *Cipher) Encrypt(data string, mode McryptMode, encode EncodeToString, padding Padding) (string, error)
Encrypt 加密
data 待加密数据 mode 加密模式: - ECB: Encrypt(data, ECB, encode, padding) - CBC: Encrypt(data, CBC, encode, padding) - CTR: Encrypt(data, CTR, encode, padding) - CFB: Encrypt(data, CFB, encode, padding) - OFB: Encrypt(data, OFB, encode, padding) encode 编码方法 padding 填充数据方法
func (*Cipher) EncryptCBC ¶
EncryptCBC 加密
func (*Cipher) EncryptCFB ¶
EncryptCFB 加密
func (*Cipher) EncryptCTR ¶
EncryptCTR 加密
func (*Cipher) EncryptECB ¶
EncryptECB 加密
type CipherOption ¶ added in v1.22.13
type CipherOption func(*cipherOptions)
CipherOption 加密器配置项
func WithIV ¶ added in v1.22.13
func WithIV(iv string) CipherOption
WithIV 设置固定IV, 如果设置了IV则以IV为准, 不随机生成IV
func WithRandIV ¶ added in v1.22.13
func WithRandIV(isRand bool) CipherOption
WithRandIV 设置是否随机生成IV, 如果设置了IV则以IV为准, 不随机生成IV
type Curl ¶
type Curl struct {
// 日志
Logger Logger
// contains filtered or unexported fields
}
func NewCurl ¶
func NewCurl(opts ...CurlOption) *Curl
func (*Curl) AddCookies ¶
AddCookies 设置cookies
func (*Curl) AddHeaders ¶
AddHeaders 对header键添加多个值
func (*Curl) AfterDone ¶ added in v1.22.13
func (c *Curl) AfterDone(f func(client *http.Client, request *http.Request, response *http.Response)) *Curl
AfterDone 请求完成后的处理方法, 如关闭连接等操作。 注意:client、request、response 有可能为nil
func (*Curl) AfterResponse ¶ added in v1.22.13
AfterResponse 请求后处理 Response
isDone 返回true 终止调用该方法之后的代码; 返回false 继续执行后续代码
func (*Curl) BeforeClient ¶ added in v1.22.13
BeforeClient 请求前处理 Client
func (*Curl) BeforeRequest ¶ added in v1.22.13
BeforeRequest 请求前处理 Request
func (*Curl) GetHeaderValues ¶
GetHeaderValues 获取header内指定键的值
func (*Curl) GetParamValues ¶
GetParamValues 获取params指定键的值
func (*Curl) InsecureSkipVerify ¶
InsecureSkipVerify 设置是否跳过https不安全验证
func (*Curl) ReSetHeader ¶
ReSetHeader 重置header
func (*Curl) SetBasicAuth ¶
SetBasicAuth 设置Basic认证的账号及密码
func (*Curl) SetContentType ¶
SetContentType 设置请求头 Content-Type
contentType 类型:"application/x-www-form-urlencoded", "application/json", "multipart/form-data", "text/plain"
func (*Curl) SetCookies ¶
SetCookies 设置cookies
func (*Curl) SetDefLogOutput ¶ added in v1.21.0
SetDefLogOutput 打印默认日志(INFO及以下级别日志: true 打印, false 禁止打印
func (*Curl) SetHeaders ¶
SetHeaders 设置header键值对
func (*Curl) SetMaxRetry ¶ added in v1.21.0
SetMaxRetry 设置失败重连次数
func (*Curl) SetRequestId ¶
SetRequestId 设置RequestId
func (*Curl) SetStatusCode ¶
SetStatusCode 设置返回状态码,除200以外需特殊处理的状态码
func (*Curl) SetUserAgent ¶
SetUserAgent 设置请求头 User-Agent
type CurlOption ¶ added in v1.22.13
type CurlOption func(*Curl)
CurlOption Curl配置项
func WithCurlBasicAuth ¶ added in v1.22.13
func WithCurlBasicAuth(username, password string) CurlOption
WithCurlBasicAuth 设置 BasicAuth 账号密码
func WithCurlBody ¶ added in v1.22.13
func WithCurlBody(body io.Reader) CurlOption
WithCurlBody 设置请求体
func WithCurlBodyBytes ¶ added in v1.22.13
func WithCurlBodyBytes(body []byte) CurlOption
WithCurlBodyBytes 设置请求体字节
func WithCurlCertKey ¶ added in v1.22.13
func WithCurlCertKey(cert, key string) CurlOption
WithCurlCertKey 设置证书和秘钥
func WithCurlContentType ¶ added in v1.22.13
func WithCurlContentType(contentType string) CurlOption
WithCurlContentType 设置请求头 Content-Type
func WithCurlCookies ¶ added in v1.22.13
func WithCurlCookies(cookies ...*http.Cookie) CurlOption
WithCurlCookies 设置请求 Cookie
func WithCurlDefLogOutput ¶ added in v1.22.13
func WithCurlDefLogOutput(enable bool) CurlOption
WithCurlDefLogOutput 设置默认日志输出开关
func WithCurlDump ¶ added in v1.22.13
func WithCurlDump(dump bool) CurlOption
WithCurlDump 设置是否开启 dump 模式
func WithCurlDumpBodyLimit ¶ added in v1.22.13
func WithCurlDumpBodyLimit(limit int64) CurlOption
WithCurlDumpBodyLimit 设置 dump 预览内容长度上限
func WithCurlHeader ¶ added in v1.22.13
func WithCurlHeader(key, value string) CurlOption
WithCurlHeader 设置请求头键值
func WithCurlHeaders ¶ added in v1.22.13
func WithCurlHeaders(headers map[string]string) CurlOption
WithCurlHeaders 批量设置请求头键值
func WithCurlInsecureSkipVerify ¶ added in v1.22.13
func WithCurlInsecureSkipVerify(isSkip bool) CurlOption
WithCurlInsecureSkipVerify 设置是否跳过 HTTPS 验证
func WithCurlLogger ¶ added in v1.22.13
func WithCurlLogger(logger Logger) CurlOption
WithCurlLogger 设置日志对象
func WithCurlMaxRetry ¶ added in v1.22.13
func WithCurlMaxRetry(max uint8) CurlOption
WithCurlMaxRetry 设置失败重试次数
func WithCurlParams ¶ added in v1.22.13
func WithCurlParams(params map[string]string) CurlOption
WithCurlParams 批量设置请求参数
func WithCurlProxyURL ¶ added in v1.22.13
func WithCurlProxyURL(proxyURL string) CurlOption
WithCurlProxyURL 设置代理地址
func WithCurlRequestId ¶ added in v1.22.13
func WithCurlRequestId(requestId string) CurlOption
WithCurlRequestId 设置请求ID
func WithCurlRootCAs ¶ added in v1.22.13
func WithCurlRootCAs(rootCAs string) CurlOption
WithCurlRootCAs 设置根证书路径
func WithCurlStatusCode ¶ added in v1.22.13
func WithCurlStatusCode(statusCode ...int) CurlOption
WithCurlStatusCode 设置可接受的状态码
func WithCurlTimeout ¶ added in v1.22.13
func WithCurlTimeout(timeout time.Duration) CurlOption
WithCurlTimeout 设置默认超时时间
type DecodeString ¶ added in v1.22.13
DecodeString 解密方法
- hex.DecodeString
- base64.StdEncoding.DecodeString
type EncodeToString ¶ added in v1.22.13
EncodeToString 加密方法
- hex.EncodeToString
- base64.StdEncoding.EncodeToString
type FileInfo ¶
FileInfo 文件信息
func FindFiles ¶
FindFiles 获取目录下所有匹配文件
path 目录 depth 深度查找: true 采用filepath.WalkDir遍历; false 只在当前目录查找 match 匹配规则: - `无参` : 匹配所有文件名 FindFiles(path, depth) - `*` : 匹配所有文件名 FindFiles(path, depth, `*`) - `文件完整名` : 精准匹配文件名 FindFiles(path, depth, fullFileName) - `e`, `文件完整名` : 精准匹配文件名 FindFiles(path, depth, `e`, fullFileName) - `p`, `文件前缀名` : 匹配前缀文件名 FindFiles(path, depth, `p`, fileNamePrefix) - `s`, `文件后缀名` : 匹配后缀文件名 FindFiles(path, depth, `s`, fileNameSuffix) - `r`, `正则表达式` : 正则匹配文件名 FindFiles(path, depth, `r`, fileNameReg)
type Form ¶
Form 表单
type LogLevel ¶ added in v1.22.13
type LogLevel int
LogLevel 日志级别类型,兼容各种第三方日志库
const ( // LevelDebug 调试级别 (-4 对应 slog.LevelDebug) LevelDebug LogLevel = -4 // LevelInfo 信息级别 (0 对应 slog.LevelInfo) LevelInfo LogLevel = 0 // LevelWarn 警告级别 (4 对应 slog.LevelWarn) LevelWarn LogLevel = 4 // LevelError 错误级别 (8 对应 slog.LevelError) // 这些值与 slog.Level 保持一致,以便内部默认实现的平滑转换 LevelError LogLevel = 8 )
type Logger ¶ added in v1.22.13
type Logger interface {
// Debug 调试级别日志
Debug(msg string, args ...any)
// Info 信息级别日志
Info(msg string, args ...any)
// Warn 警告级别日志
Warn(msg string, args ...any)
// Error 错误级别日志
Error(msg string, args ...any)
// With 创建携带附加字段的子 Logger
With(args ...any) Logger
// Enabled 判断指定级别的日志是否启用
Enabled(ctx context.Context, level LogLevel) bool
}
Logger 日志接口,可通过 Configure 设置自定义实现,若未设置则默认使用 log/slog 标准库。 该接口设计为与第三方日志库(如 zap、logrus 等)兼容。
func Log ¶ added in v1.22.13
func Log() Logger
Log 获取全局 Logger 实例。 若未通过 Configure 设置自定义 Logger,则返回基于 log/slog 标准库的默认实现。
兼容第三方日志库说明: 本库 Logger 接口设计兼容 log/slog。若需使用 zap、logrus 等第三方库, 需编写适配器实现 Logger 接口,并通过 Configure(WithLogger(adapter)) 注入。 Example (Zap):
type ZapAdapter struct { l *zap.Logger }
func (z *ZapAdapter) Debug(msg string, args ...any) { ... }
func (z *ZapAdapter) Enabled(ctx context.Context, level LogLevel) bool { ... }
type McryptMode ¶
type McryptMode int8
McryptMode 密码模式
const ( ECB McryptMode = iota // 0 电码本模式(Electronic Codebook Book,ECB),ECB无须设置初始化向量IV CBC // 1 密码分组链接模式(Cipher Block Chaining ,CBC),如果明文长度不是分组长度16字节(des 8字节)的整数倍需要进行填充 CTR // 2 计算器模式(Counter,CTR) CFB // 3 密码反馈模式(Cipher FeedBack,CFB) OFB // 4 输出反馈模式(Output FeedBack,OFB) )
加密模式
type Once ¶ added in v1.22.13
type Once struct {
// contains filtered or unexported fields
}
type Option ¶ added in v1.22.13
type Option func(*options)
Option 用于配置全局设置入口的选项
func WithLogger ¶ added in v1.22.13
WithLogger 设置自定义 Logger,若未设置则默认使用 log/slog 标准库。
type Pool ¶ added in v1.22.11
type Pool[T any] struct { // contains filtered or unexported fields }
func NewPool ¶ added in v1.22.11
func NewPool[T any](newFn func() *T, opts ...PoolOption[T]) *Pool[T]
type PoolOption ¶ added in v1.22.13
PoolOption 对象池配置项
func WithPoolReset ¶ added in v1.22.13
func WithPoolReset[T any](resetFn func(*T)) PoolOption[T]
WithPoolReset 设置对象重置函数
type RSA ¶
type RSA struct {
// contains filtered or unexported fields
}
func (*RSA) Decrypt ¶
func (r *RSA) Decrypt(encrypt string, decode DecodeString) (string, error)
Decrypt 解密(私钥)
encrypt 代解密数据 decode 解码方法
func (*RSA) DecryptOAEP ¶ added in v1.21.5
DecryptOAEP 解密(私钥)
encrypt 代解密数据 decode 解码方法 hash OAEP编码方法
func (*RSA) Encrypt ¶
func (r *RSA) Encrypt(data string, encode EncodeToString) (string, error)
Encrypt 加密(公钥)
data 待加密数据 encode 编码方法
func (*RSA) IsSetPrivateKey ¶
IsSetPrivateKey 是否正确设置 PrivateKey
func (*RSA) Sign ¶
Sign 签名(私钥)
data 待签名数据 hash 加密哈希函数标识: - crypto.SHA256 : Sign(data, crypto.SHA256, encode) - crypto.MD5 : Sign(data, crypto.MD5, encode) encode - 编码方法
func (*RSA) SignPSS ¶ added in v1.21.5
func (r *RSA) SignPSS(data string, hash crypto.Hash, encode EncodeToString, opts *rsa.PSSOptions) (string, error)
SignPSS 签名(私钥)
data 待签名数据 hash 加密哈希函数标识: - crypto.SHA256 : Sign(data, crypto.SHA256, encode) - crypto.MD5 : Sign(data, crypto.MD5, encode) encode - 编码方法 opts - *rsa.PSSOptions
func (*RSA) Verify ¶
Verify 验证签名(公钥)
data 待验证数据 sign 签名串 hash 加密哈希函数标识: - crypto.SHA256 : Verify(data, signature, crypto.SHA256, decode) - crypto.MD5 : Verify(data, signature, crypto.MD5, decode) decode 解码方法
func (*RSA) VerifyPSS ¶ added in v1.21.5
func (r *RSA) VerifyPSS(data, sign string, hash crypto.Hash, decode DecodeString, opts *rsa.PSSOptions) error
VerifyPSS 验证签名(公钥)
data 待验证数据 sign 签名串 hash 加密哈希函数标识: - crypto.SHA256 : Verify(data, signature, crypto.SHA256, decode) - crypto.MD5 : Verify(data, signature, crypto.MD5, decode) decode 解码方法
type RSAOption ¶ added in v1.22.13
type RSAOption func(*rsaOptions)
RSAOption RSA配置项
func WithRSAFilePath ¶ added in v1.22.13
WithRSAFilePath 指定密钥参数是否为文件路径
type ReadBlock ¶
ReadBlock 处理读取的数据块
- size 读取的数据块大小
- block 读取的数据块 返回值 - error 处理错误信息: 返回的 error == DONE 代表正确处理完数据并终止扫描
type ReadLine ¶
ReadLine 处理scan扫描的行数据
- num 行号: 当前扫描到第几行
- line 行数据: 当前扫描的行数据
- lineDone 当前行(num)数据是否读取完毕: true 当前行(num)数据读取完毕; false 当前行(num)数据未读完 返回值 - error 处理错误信息: 返回的 error == DONE 代表正确处理完数据并终止扫描
type ReadScan ¶
ReadScan 处理scan扫描的行数据
- num 行号: 当前扫描到第几行
- line 行数据: 当前扫描的行数据
- WrapError 扫描错误信息 返回值 - error 处理错误信息: 返回的 error == DONE 代表正确处理完数据并终止扫描
type Response ¶
type Response struct {
Body
// contains filtered or unexported fields
}
func Json ¶ added in v1.22.13
func Json(w http.ResponseWriter, opts ...ResponseOption) *Response
Json 响应Json数据
Example ¶
// 响应json数据
serveMux.HandleFunc("/response/json", func(w http.ResponseWriter, r *http.Request) {
// 获取URL查询字符串参数
queryParam := r.URL.Query().Get("v")
// 响应的数据
user := User{
Name: "张三",
Age: 22,
Sex: "男",
IsMarried: false,
Address: "北京市",
phone: "131188889999",
}
if queryParam == "fail" {
// 错误响应
utils.Json(w, utils.WithStatusCode(http.StatusNotAcceptable)).Fail(20000, "fail")
return
}
// 成功响应
utils.Json(w).Success(10000, user)
})
func View ¶
func View(w http.ResponseWriter, opts ...ResponseOption) *Response
View 响应文本视图
Example ¶
// 响应html
serveMux.HandleFunc("/response/html", func(w http.ResponseWriter, r *http.Request) {
// 响应html数据
utils.View(w).Html("<p>这是一个<b style=\"color: red\">段落!</b></p>")
})
// 响应xml
serveMux.HandleFunc("/response/xml", func(w http.ResponseWriter, r *http.Request) {
// 响应的数据
user := User{
Name: "张三",
Age: 22,
Sex: "男",
IsMarried: false,
Address: "北京市",
phone: "131188889999",
}
// 响应xml数据
utils.View(w).Xml(user)
})
// 响应text
serveMux.HandleFunc("/response/text", func(w http.ResponseWriter, r *http.Request) {
// 响应text数据
utils.View(w).Text("<p>这是一个<b style=\"color: red\">段落!</b></p>")
})
// 显示image
serveMux.HandleFunc("/response/show", func(w http.ResponseWriter, r *http.Request) {
// 获取URL查询字符串参数
file := r.URL.Query().Get("file")
if utils.IsExist(file) {
// 显示文件内容
utils.View(w).Show(file)
return
}
// 处理错误
utils.View(w, utils.WithStatusCode(http.StatusNotFound)).Text("不存在的文件:" + file)
})
// 下载文件
serveMux.HandleFunc("/response/download", func(w http.ResponseWriter, r *http.Request) {
// 获取URL查询字符串参数
file := r.URL.Query().Get("file")
if utils.IsExist(file) {
// 下载文件数据
utils.View(w).Download(file)
return
}
// 处理错误
utils.View(w, utils.WithStatusCode(http.StatusNotFound)).Text("不存在的文件:" + file)
})
func (*Response) ContentType ¶
ContentType 设置响应头 Content-Type
func (*Response) StatusCode ¶
StatusCode 设置响应状态码,如:http.StatusOK
type ResponseOption ¶ added in v1.22.13
type ResponseOption func(*Response)
ResponseOption 响应配置项
func WithContentType ¶ added in v1.22.13
func WithContentType(contentType string) ResponseOption
WithContentType 设置响应头 Content-Type
func WithHeader ¶ added in v1.22.13
func WithHeader(f func(header http.Header)) ResponseOption
WithHeader 设置响应头
func WithStatusCode ¶ added in v1.22.13
func WithStatusCode(statusCode int) ResponseOption
WithStatusCode 设置响应状态码
type WriteFile ¶
WriteFile 文件读写操作
func NewWrite ¶
func NewWrite(fileName string, opts ...WriteOption) (*WriteFile, error)
NewWrite 返回一个WriteFile实例
fileName 文件路径: 不存在则创建 perm 文件权限: 默认权限 文件夹0744, 文件0644
type WriteOption ¶ added in v1.22.13
type WriteOption func(*writeOptions)
WriteOption 写入文件配置项
func WithWriteAppend ¶ added in v1.22.13
func WithWriteAppend(isAppend bool) WriteOption
WithWriteAppend 设置是否追加写入
func WithWritePerm ¶ added in v1.22.13
func WithWritePerm(perm os.FileMode) WriteOption
WithWritePerm 设置文件权限