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 ClientIPWithTrustedProxies(r *http.Request, trustedProxies *TrustedProxies) 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 comparable](s1, s2 []T) []T
- func DiffInto[T comparable](dst, 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 comparable](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 comparable](s1, s2 []T) []T
- func IntersectInto[T comparable](dst, s1, s2 []T) []T
- func IsDir(path string) bool
- func IsExist(path string) bool
- func IsFile(filepath string) bool
- func IsHas[T comparable](v T, s []T) bool
- func Line(r io.Reader, handle ReadLine) error
- func Local() *time.Location
- func LocalIP() string
- func MapDiff[K comparable, V comparable](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 comparable, V comparable](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 NoPadding(data []byte, _ int) []byte
- func NoUnPadding(data []byte) ([]byte, error)
- 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(pemText string) string
- func Replace(s string, oldnew map[string]string) string
- func Retry(maxRetries uint8, fn func(tries int) error) error
- func RetryContext(ctx context.Context, maxRetries uint8, ...) error
- func Reverse[T any](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 SecureRandStr(n int) (string, error)
- func SecureRandStr2(n int) (string, error)
- func SecureRandStr3(n int, alpha string) (string, error)
- func SecureUniqID(l uint8) (string, error)
- func ServerIP() string
- func ServerIPContext(ctx context.Context) 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 comparable, 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 URLPath(urlPath string, params url.Values) (string, error)
- 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 UniqId(l uint8, r ...*rand.Rand) stringdeprecated
- func Unique[T comparable](s []T) []T
- func UniqueInPlace[T comparable](s []T) []T
- func UniqueInto[T comparable](dst, s []T) []T
- func Unmarshal(data []byte, v any) error
- func UrlPath(urlPath string, params url.Values) (string, error)deprecated
- func WriteFileAtomic(fileName string, data []byte, perm os.FileMode) error
- func WriteStringAtomic(fileName, data string, perm os.FileMode) 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) DecryptBytes(data []byte, mode McryptMode, unPadding UnPadding) ([]byte, 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) DecryptGCM(data, additionalData []byte) ([]byte, error)
- func (c *Cipher) DecryptGCMString(encrypt string, decode DecodeString, additionalData []byte) (string, error)
- func (c *Cipher) DecryptOFB(data []byte, unPadding UnPadding) ([]byte, error)
- func (c *Cipher) DecryptTo(dst, data []byte, mode McryptMode, unPadding UnPadding) ([]byte, error)
- func (c *Cipher) Encrypt(data string, mode McryptMode, encode EncodeToString, padding Padding) (string, error)
- func (c *Cipher) EncryptBytes(data []byte, mode McryptMode, padding Padding) ([]byte, 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) EncryptGCM(data, additionalData []byte) ([]byte, error)
- func (c *Cipher) EncryptGCMString(data string, encode EncodeToString, additionalData []byte) (string, error)
- func (c *Cipher) EncryptOFB(data []byte, padding Padding) ([]byte, error)
- func (c *Cipher) EncryptTo(dst, data []byte, mode McryptMode, 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) AfterBodyContext(f func(ctx context.Context, body []byte) error) *Curl
- func (c *Curl) AfterDone(f func(client *http.Client, request *http.Request, response *http.Response)) *Curl
- func (c *Curl) AfterDoneContext(f func(ctx context.Context, client *http.Client, request *http.Request, ...)) *Curl
- func (c *Curl) AfterResponse(f func(response *http.Response) (isDone bool, err error)) *Curl
- func (c *Curl) AfterResponseContext(f func(ctx context.Context, response *http.Response) (isDone bool, err error)) *Curl
- func (c *Curl) BeforeClient(f func(client *http.Client) error) *Curl
- func (c *Curl) BeforeClientContext(f func(ctx context.Context, client *http.Client) error) *Curl
- func (c *Curl) BeforeRequest(f func(request *http.Request) error) *Curl
- func (c *Curl) BeforeRequestContext(f func(ctx context.Context, request *http.Request) error) *Curl
- func (c *Curl) ClearCookies() *Curl
- func (c *Curl) Clone() (*Curl, error)
- 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) DeleteContext(ctx context.Context, url string) (err error)
- func (c *Curl) Get(url string) (err error)
- func (c *Curl) GetContext(ctx context.Context, 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) GetRequestId() stringdeprecated
- func (c *Curl) GetStatusCode() []int
- 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) HeadContext(ctx context.Context, url string) error
- func (c *Curl) InsecureSkipVerify(isSkip bool) *Curl
- func (c *Curl) NewRequest() (*Curl, error)
- func (c *Curl) Options(url string) (err error)
- func (c *Curl) OptionsContext(ctx context.Context, url string) (err error)
- func (c *Curl) Patch(url string) (err error)
- func (c *Curl) PatchContext(ctx context.Context, url string) (err error)
- func (c *Curl) Post(url string) (err error)
- func (c *Curl) PostContext(ctx context.Context, url string) (err error)
- func (c *Curl) PostForm(url string) error
- func (c *Curl) PostFormContext(ctx context.Context, url string) error
- func (c *Curl) Put(url string) (err error)
- func (c *Curl) PutContext(ctx context.Context, 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) SendContext(ctx context.Context, 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) SetLogBodyLimit(limit int64) *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) SetRequestId(requestId ...string) *Curldeprecated
- 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 WithCurlLogBodyLimit(limit int64) 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 WithCurlRequestId(requestId string) CurlOptiondeprecated
- 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(fieldName 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(fieldNames ...string)
- func (f *Form) DelParams(keys ...string)
- func (f *Form) Reader() (body io.Reader, contentType string, err error)
- func (f *Form) SetFile(fieldName, filePath string) *Form
- func (f *Form) SetFiles(files map[string]string) *Form
- func (f *Form) SetMaxSingleFileSize(limit int64) *Form
- func (f *Form) SetMaxTotalFileSize(limit int64) *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) DecryptOAEPHash(encrypt string, decode DecodeString, hashID crypto.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) EncryptOAEPHash(data string, encode EncodeToString, hashID crypto.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 Replacer
- type Response
- func (r *Response) ContentType(contentType string) *Response
- func (r *Response) Download(filePath string, rename ...string)
- func (r *Response) DownloadRequest(req *http.Request, 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) ShowRequest(req *http.Request, 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 TrustedProxies
- type UnPadding
- type Unsigned
- type ValidationError
- type ValidationReason
- 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" // 年份格式:4 位数字 MonthTime = YearTime + "01" // 年月格式:YYYYMM DayTime = MonthTime + "02" // 年月日格式:YYYYMMDD HourTime = DayTime + " 15" // 年月日时格式:YYYYMMDDHH MinuteTime = HourTime + "04" // 年月日时分格式:YYYYMMDDHHMM SecondTime = MinuteTime + "05" // 年月日时分秒格式:YYYYMMDDHHMMSS )
时间格式化模板常量。 用于 time.Time.Format 方法,格式遵循 Go 的参考时间 "2006-01-02 15:04: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 AddPEMHeaders ¶ added in v1.21.5
AddPEMHeaders 为 RSA 密钥串添加 PEM 头尾标记。
keyType 支持 public/private。
func AddTime ¶ added in v1.21.4
AddTime 对时间进行增减计算。 支持的时间单位:Y(年)、M(月)、D(日)、H(时)、I(分)、S(秒)、L(毫秒)、C(微秒)、N(纳秒)。 使用 + 或 - 前缀表示增加或减少。
参数说明:
- t:原始时间
- addTimes:增减时间列表,如 "-1D"、"+2H"、"1M"
返回值:计算后的时间,错误信息
示例:
AddTime(t, "-1D", "+2H", "30S") // 减1天,加2小时,加30秒
func After ¶
After 比较 t1 是否在 t2 之后。
参数说明:
- layout:时间格式化模板
- t1:第一个时间字符串
- t2:第二个时间字符串
返回值:true 表示 t1 在 t2 之后,错误信息
func Before ¶
Before 比较 t1 是否在 t2 之前。
参数说明:
- layout:时间格式化模板
- t1:第一个时间字符串
- t2:第二个时间字符串
返回值:true 表示 t1 在 t2 之前,错误信息
func CheckDate ¶
CheckDate 验证日期是否合法。
参数说明:
- year:年份(1-32767)
- month:月份(1-12)
- day:日期(1-31)
返回值:true 表示日期合法
func ClientIP ¶
ClientIP 获取客户端 IP 地址。 默认仅在请求来自回环地址时信任转发头,生产环境建议使用 ClientIPWithTrustedProxies 显式配置白名单。
参数说明:
- r:HTTP 请求对象
返回值:客户端 IP 地址字符串
func ClientIPWithTrustedProxies ¶ added in v1.22.15
func ClientIPWithTrustedProxies(r *http.Request, trustedProxies *TrustedProxies) string
ClientIPWithTrustedProxies 使用显式可信代理白名单解析客户端 IP。 仅当 RemoteAddr 命中 trustedProxies 时才信任 `X-Forwarded-For` / `X-Real-Ip`。
参数说明:
- r:HTTP 请求对象
- trustedProxies:可信代理白名单
返回值:客户端 IP 地址字符串
func Date ¶
Date 使用 patterns 规则格式化时间。 patterns 支持 PHP 风格的格式化符(如 Y-m-d H:i:s)。
参数说明:
- timeZone:目标时区
- layout:格式化模板
- timestamp:可变参数,Unix 时间戳
返回值:格式化后的时间字符串
示例:
Date(CST(), "Y-m-d H:i:s", 1700000000) // "2023-11-15 01:46:40"
func DateInfo ¶
DateInfo 获取时间的详细信息映射表。
参数说明:
- t:待解析的时间
返回值:包含年月日时分秒、周信息、时间戳等的 map
返回值字段说明:
- year: 年份
- month: 月份(1-12)
- monthEn: 英文月份
- day: 日期
- hour: 小时(0-23)
- minute: 分钟(0-59)
- second: 秒数(0-59)
- millisecond: 毫秒
- microsecond: 微秒
- nanosecond: 纳秒
- unix: 时间戳(秒)
- unixNano: 时间戳(纳秒)
- weekDay: 星期几(0-6,0 为周日)
- weekDayEn: 英文星期
- yearWeek: 一年中第几周
- yearDay: 一年中第几天
- date: 格式化日期 "2006-01-02 15:04:05"
- dateNs: 格式化日期(纳秒精度)"2006-01-02T15:04:05.999999999Z07:00"
func Diff ¶ added in v1.22.0
func Diff[T comparable](s1, s2 []T) []T
Diff 计算 s1 与 s2 的差集,即 s1 中有而 s2 中没有的元素。 返回结果保持 s1 原有顺序,并保留 s1 中原本存在的重复值。
func DiffInto ¶ added in v1.22.19
func DiffInto[T comparable](dst, s1, s2 []T) []T
DiffInto 将 s1 与 s2 的差集追加到 dst,并返回复用后的结果切片。 s2 被视为排除集合;返回结果保持 s1 顺序与重复值,适合权限、标签、状态列表等保序过滤场景。
func DrainBody ¶
func DrainBody(b io.ReadCloser) ([]byte, io.ReadCloser, error)
DrainBody 读取 body 内容并恢复原始流。
参数说明:
- b:io.ReadCloser
返回值:body 内容、恢复的 ReadCloser、错误信息
func GenerateKeyRSA ¶
GenerateKeyRSA 生成 RSA 密钥文件。
path 为密钥存放目录;bits 为密钥位数;生产环境要求至少 2048。 pkcs[0] 控制公钥格式是否为 PKCS8,默认 true;pkcs[1] 控制私钥格式是否为 PKCS1,默认 true。
func GetEnv ¶
GetEnv 获取环境变量值。 如果环境变量未设置或值为空,且提供了默认值参数,则返回默认值。
参数说明:
- key:环境变量名
- defaultVal:可选的默认值,当环境变量未设置时返回
返回值:环境变量值或默认值
func GetFunctionName ¶ added in v1.22.12
func GetFunctionName(i interface{}) string
GetFunctionName 获取函数名(普通函数、结构体方法或匿名函数)
func Intersect ¶ added in v1.22.0
func Intersect[T comparable](s1, s2 []T) []T
Intersect 计算 s1 与 s2 的交集,即 s1 中有而 s2 中也有的元素。 返回结果保持 s1 原有顺序,并保留 s1 中原本存在的重复值。
func IntersectInto ¶ added in v1.22.19
func IntersectInto[T comparable](dst, s1, s2 []T) []T
IntersectInto 将 s1 与 s2 的交集追加到 dst,并返回复用后的结果切片。 s2 被视为命中集合;返回结果保持 s1 顺序与重复值,适合按白名单过滤但不打乱业务排序的场景。
func IsHas ¶
func IsHas[T comparable](v T, s []T) bool
IsHas 检查 s 中是否存在 v。1.21 版本以上推荐使用标准库 slices.Contains(s, v)。
func LocalIP ¶
func LocalIP() string
LocalIP 获取本机 IP 地址。 优先返回主机名对应的 IPv4 地址,如果获取失败则遍历网络接口。
返回值:本地 IP 地址字符串,获取失败返回空字符串
func MapDiff ¶
func MapDiff[K comparable, V comparable](m1, m2 map[K]V) []V
MapDiff 计算 m1 与 m2 的值差集,即 m1 中有但 m2 中没有的值。 返回结果保留 m1 原有遍历结果中的重复值。
func MapDiffKey ¶
MapDiffKey 计算m1与m2的键差集即m1中有但m2中没有的键
func MapIntersect ¶
func MapIntersect[K comparable, V comparable](m1, m2 map[K]V) []V
MapIntersect 计算 m1 与 m2 的值交集,即 m1 与 m2 都有的值。 返回结果保留 m1 原有遍历结果中的重复值。
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 NoPadding ¶ added in v1.22.15
NoPadding 表示不做任何填充,适合 CTR/CFB/OFB/GCM 等流式或 AEAD 模式。 返回值会复制原始数据,避免调用方后续修改原切片影响加密流程。
func NoUnPadding ¶ added in v1.22.15
NoUnPadding 表示不做任何去填充,适合 CTR/CFB/OFB/GCM 等流式或 AEAD 模式。 返回值会复制原始数据,避免调用方后续修改结果影响后续处理。
func NumberFormat ¶
NumberFormat 以千位分隔符方式格式化一个数字
number 要格式化的数字 decimals 保留几位小数 decPoint 小数点[.] thousandsSep 千位分隔符[,]
func Rand ¶
Rand 返回 min ~ max 之间的随机数,返回值可能包含 min 和 max。
参数说明:
- minInt:最小值
- maxInt:最大值
- r:可选的随机数生成器,批量生成时传入 r 参数可提升生成随机数效率
返回值:min ~ max 之间的随机整数
func RandStr ¶
RandStr 随机生成字符串,使用 ALPHA 规则。 注意:该函数基于 math/rand,仅适用于测试数据、临时标识等非安全场景。 禁止用于 token、验证码、重置链接、签名密钥等安全敏感用途;安全场景请使用 SecureRandStr。
n 生成字符串长度 r 随机种子 rand.NewSource(time.Now().UnixNano()) : 批量生成时传入r参数可提升生成随机数效率
func RandStr2 ¶
RandStr2 随机生成字符串,使用 ALNUM 规则。 为兼容旧行为,首字符固定从 ALPHA 中选择,避免数字开头。 注意:该函数基于 math/rand,仅适用于测试数据、临时标识等非安全场景。 禁止用于 token、验证码、重置链接、签名密钥等安全敏感用途;安全场景请使用 SecureRandStr2。
n 生成字符串长度 r 随机种子 rand.NewSource(time.Now().UnixNano()) : 批量生成时传入r参数可提升生成随机数效率
func RandStr3 ¶
RandStr3 随机生成字符串。 注意:该函数基于 math/rand,仅适用于测试数据、临时标识等非安全场景。 禁止用于 token、验证码、重置链接、签名密钥等安全敏感用途;安全场景请使用 SecureRandStr3。
n 生成字符串长度 alpha 生成随机字符串的种子 r 随机种子 rand.NewSource(time.Now().UnixNano()) : 批量生成时传入r参数可提升生成随机数效率
func Redirect ¶
func Redirect(w http.ResponseWriter, url string, opts ...ResponseOption)
Redirect 重定向。
url 为重定向地址。状态码仅接受 3xx,非 3xx 会回退为 302。
Example ¶
serveMux.HandleFunc("/response/redirect", func(w http.ResponseWriter, r *http.Request) {
// 重定向
utils.Redirect(w, "/response/json")
})
func RemovePEMHeaders ¶ added in v1.21.5
RemovePEMHeaders 去掉 PEM 头尾标记和空白字符。
func Retry ¶ added in v1.22.12
Retry 尝试执行 fn,如果 fn 返回错误则按指数退避策略重试。 maxRetries 表示最大尝试次数,包含首次执行。 重试间隔从 100ms~200ms 区间起步,按 2 倍递增,并在每次退避上附加随机抖动,最大不超过 3s。
func RetryContext ¶ added in v1.22.17
func RetryContext(ctx context.Context, maxRetries uint8, fn func(ctx context.Context, tries int) error) error
RetryContext 尝试执行 fn,如果 fn 返回错误则按指数退避策略重试。 当 ctx 被取消时,会立即中断后续重试与等待。
func RootCAs ¶
RootCAs 设置根证书池。 默认会在系统根证书池基础上追加自定义根证书,避免误把系统根证书整体替换掉。
参数说明:
- config:TLS 配置
- rootCAs:根证书文件路径
返回值:错误信息
func SecureRandStr ¶ added in v1.22.17
SecureRandStr 使用密码学安全随机源生成字符串,使用 ALPHA 规则。
参数说明:
- n:生成字符串长度
返回值:随机字符串、错误信息
func SecureRandStr2 ¶ added in v1.22.17
SecureRandStr2 使用密码学安全随机源生成字符串,使用 ALNUM 规则。 为兼容历史命名习惯,首字符固定从 ALPHA 中选择,避免数字开头。
参数说明:
- n:生成字符串长度
返回值:随机字符串、错误信息
func SecureRandStr3 ¶ added in v1.22.17
SecureRandStr3 使用密码学安全随机源按自定义字符集生成字符串。
参数说明:
- n:生成字符串长度
- alpha:候选字符集
返回值:随机字符串、错误信息
func SecureUniqID ¶ added in v1.22.17
SecureUniqID 使用密码学安全随机源生成长度范围 16-32 位的字符串标识。 与 UniqID 不同,SecureUniqID 不依赖时间戳,不保证可排序。
参数说明:
- l:生成长度,取值范围 [16-32]
返回值:随机字符串、错误信息
func ServerIP ¶
func ServerIP() string
ServerIP 获取服务器对外 IP 地址。 默认优先返回缓存值或本地网卡 IP,避免在热路径上频繁拨号外网地址。 如需自定义超时控制,可使用 ServerIPContext。
返回值:服务器对外 IP 地址字符串,获取失败返回空字符串
func ServerIPContext ¶ added in v1.22.17
ServerIPContext 获取服务器出站 IP 地址,并允许调用方控制超时。 默认优先返回缓存值或本地网卡 IP,仅在本地 IP 不可用时才回退到 UDP 探测。
参数说明:
- ctx:上下文,可用于控制超时或取消
返回值:服务器出站 IP 地址字符串,获取失败返回空字符串
func Strtotime ¶
Strtotime 解析时间字符串(智能解析)。 支持多种常见格式自动识别,也支持指定格式解析。
参数说明:
- timeZone:目标时区
- parse:可变参数,第一个为格式化模板,第二个为时间字符串
返回值:解析后的时间,错误信息
示例:
Strtotime(CST(), "2006-01-02 15:04:05") // 当前时间(如果解析失败) Strtotime(CST(), "2006-01-02 15:04:05", "2024-01-01 12:00:00") // 指定时间 Strtotime(CST(), "Y-m-d H:i:s") // 当前时间
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:格式化模板,如 "2006-01-02 15:04:05"
- timestamp:可变参数,Unix 时间戳(秒),支持传入纳秒
返回值:格式化后的时间字符串
示例:
TimeFormat(CST(), "2006-01-02 15:04:05", 1700000000) TimeFormat(CST(), "2006-01-02 15:04:05", 1700000000000000000) // 纳秒时间戳
func TimeParse ¶
TimeParse 解析时间字符串为 time.Time。
参数说明:
- timeZone:目标时区
- layout:格式化模板
- timeStr:时间字符串
返回值:解析后的时间,错误信息
func URLPath ¶ added in v1.22.15
URLPath 组装带参数的完整 URL。 将 params 中的查询参数合并到 urlPath 中,保留原有查询参数。
参数说明:
- urlPath:基础 URL 路径
- params:查询参数键值对
返回值:完整 URL 字符串,错误信息
func UniqID ¶ added in v1.22.15
UniqID 生成一个长度范围 16-32 位的唯一 ID 字符串(可排序字符串)。 UniqID 只生成字符串标识,不承诺全局强唯一;强唯一场景建议使用业务唯一键或 UUID/ULID。 注意:该函数基于时间戳与 math/rand,仅适用于非安全场景。 禁止用于 token、验证码、重置链接等安全敏感用途;安全场景请使用 SecureUniqID。
l 生成 UniqID 长度: 取值范围[16-32], 小于16按16位处理, 大于32按32位处理 r 随机种子 rand.NewSource(time.Now().UnixNano()) : 批量生成时传入r参数可提升生成随机数效率
func Unique ¶ added in v1.22.0
func Unique[T comparable](s []T) []T
Unique 去除 s 中重复的值。 返回结果保持首个元素出现顺序;返回切片使用新的底层数组,避免调用方误改原始数据。
func UniqueInPlace ¶ added in v1.22.19
func UniqueInPlace[T comparable](s []T) []T
UniqueInPlace 在 s 的原始底层数组上完成去重并返回结果切片。 业务意图:调用方明确不再需要原始顺序完整数据时,可用该入口省掉结果切片分配;边界是返回后 s 尾部旧数据不可再视为有效结果。
func UniqueInto ¶ added in v1.22.19
func UniqueInto[T comparable](dst, s []T) []T
UniqueInto 将 s 去重后追加到 dst,并返回复用后的结果切片。 dst 的历史内容会被清空但容量会被复用;适合循环内批量处理时降低临时切片分配。
func WriteFileAtomic ¶ added in v1.22.17
WriteFileAtomic 原子写入完整文件内容。 适用于配置文件、密钥文件、状态文件等需要“覆盖即完整替换”的场景。 内部使用同目录临时文件 + Sync + Close + Rename,避免直接 O_TRUNC 截断目标文件。
参数说明:
- fileName:目标文件路径
- data:完整文件内容
- perm:文件权限
func WriteStringAtomic ¶ added in v1.22.17
WriteStringAtomic 原子写入完整字符串内容。 适用于希望以字符串形式原子覆盖目标文件的场景。
参数说明:
- fileName:目标文件路径
- data:完整字符串内容
- perm:文件权限
func ZeroPadding ¶
ZeroPadding 使用 0 字节填充到分组大小的整数倍。
注意:ZeroPadding 无法区分明文末尾真实的 0 字节和填充字节,协议允许时优先使用 PKCS#7。
Types ¶
type Body ¶
type Body struct {
Success bool `json:"success"` // 响应状态:true 成功,false 失败
Code int `json:"code"` // 业务识别码
Message string `json:"message"` // 响应信息
Data any `json:"data"` // 响应数据
}
Body JSON 响应体。
type Cipher ¶
type Cipher struct {
// contains filtered or unexported fields
}
Cipher 是 AES/DES/3DES 的通用分组加密器。
架构说明:
- key 和固定 IV 在构造后只读,Encrypt/Decrypt 过程中不再修改对象状态,便于并发复用。
- WithRandIV(true) 时,加密会把随机 IV 写入密文头部,解密会从密文头部读取 IV。
- ECB、非认证流模式与“未显式设置 IV 时使用 key 派生 IV”都属于兼容旧系统的保留能力,默认禁用。
- 公开 API 同时支持传统 padding 语义和 `NoPadding/NoUnPadding` 零额外拷贝路径。
func DES ¶
func DES(key string, opts ...CipherOption) (*Cipher, error)
DES 创建 DES/3DES 分组密码封装。
安全说明:DES 密钥空间过小,3DES 也属于历史兼容算法;新系统应优先使用 AES-GCM。 当 key 长度为 24 字节时自动使用 3DES,长度为 8 字节时使用 DES。
key 秘钥
func DES3 ¶
func DES3(key string, opts ...CipherOption) (*Cipher, error)
DES3 创建 3DES 分组密码封装。
安全说明:3DES 仅用于旧协议兼容,新系统应优先使用 AES-GCM。
key 秘钥
func NewCipher ¶
func NewCipher(key string, block CipherBlock, opts ...CipherOption) (*Cipher, error)
NewCipher 创建通用分组加密器。
key 为原始密钥字符串;block 通常传 aes.NewCipher、des.NewCipher 或 des.NewTripleDESCipher。
func (*Cipher) Decrypt ¶
func (c *Cipher) Decrypt(encrypt string, mode McryptMode, decode DecodeString, unPadding UnPadding) (string, error)
Decrypt 解密编码后的密文字符串。
encrypt 为待解密数据;decode 为解码方法;unPadding 为去填充方法。
func (*Cipher) DecryptBytes ¶ added in v1.22.15
DecryptBytes 解密原始密文字节。
参数说明:
- data:待解密密文。
- mode:解密模式。
- unPadding:去填充函数。
返回值:明文字节,错误信息。
func (*Cipher) DecryptCBC ¶
DecryptCBC 使用 CBC 模式解密。
参数说明:
- data:待解密密文。
- unPadding:去填充函数。
返回值:明文字节,错误信息。
func (*Cipher) DecryptCFB ¶
DecryptCFB 使用 CFB 模式解密。
参数说明:
- data:待解密密文。
- unPadding:去填充函数。
返回值:明文字节,错误信息。
func (*Cipher) DecryptCTR ¶
DecryptCTR 使用 CTR 模式解密。
参数说明:
- data:待解密密文。
- unPadding:去填充函数。
返回值:明文字节,错误信息。
func (*Cipher) DecryptECB ¶
DecryptECB 使用 ECB 模式解密。
参数说明:
- data:待解密密文。
- unPadding:去填充函数。
返回值:明文字节,错误信息。
func (*Cipher) DecryptGCM ¶ added in v1.22.15
DecryptGCM 使用 GCM(AEAD) 模式解密。
参数说明:
- data:nonce + 密文字节。
- additionalData:附加认证数据,可为空;加解密两端必须完全一致。
返回值:明文字节,错误信息。
func (*Cipher) DecryptGCMString ¶ added in v1.22.15
func (c *Cipher) DecryptGCMString(encrypt string, decode DecodeString, additionalData []byte) (string, error)
DecryptGCMString 使用 GCM 模式解密编码后的密文字符串。
func (*Cipher) DecryptOFB ¶
DecryptOFB 使用 OFB 模式解密。
参数说明:
- data:待解密密文。
- unPadding:去填充函数。
返回值:明文字节,错误信息。
func (*Cipher) DecryptTo ¶ added in v1.22.19
DecryptTo 将解密结果追加到 dst 并返回结果切片。 业务意图:高频解密场景可复用调用方缓冲区,减少明文字节切片分配;CTR/CFB/OFB 且 NoUnPadding 时走直接写入快路径。
参数说明:
- dst:调用方提供的输出缓冲区,历史内容会保留,新明文追加在末尾。
- data:待解密密文,不能与 dst 的可写容量部分重叠,避免流解密覆盖尚未读取的密文。
- mode:解密模式。
- unPadding:去填充函数。
返回值:追加明文后的 dst,错误信息。
func (*Cipher) Encrypt ¶
func (c *Cipher) Encrypt(data string, mode McryptMode, encode EncodeToString, padding Padding) (string, error)
Encrypt 加密字符串并编码输出。
data 为待加密数据;mode 为加密模式;encode 为编码方法;padding 为填充方法。
func (*Cipher) EncryptBytes ¶ added in v1.22.15
EncryptBytes 加密字节数据并返回原始密文字节。
该方法适合业务层自行选择编码方式,可避免 string 与 []byte 的额外转换。
参数说明:
- data:待加密原始数据。
- mode:加密模式。
- padding:填充函数。
返回值:密文字节,错误信息。
func (*Cipher) EncryptCBC ¶
EncryptCBC 使用 CBC 模式加密。
参数说明:
- data:待加密原始数据。
- padding:填充函数。
返回值:密文字节,错误信息。
func (*Cipher) EncryptCFB ¶
EncryptCFB 使用 CFB 模式加密。
参数说明:
- data:待加密原始数据。
- padding:填充函数。
返回值:密文字节,错误信息。
func (*Cipher) EncryptCTR ¶
EncryptCTR 使用 CTR 模式加密。
参数说明:
- data:待加密原始数据。
- padding:填充函数。
返回值:密文字节,错误信息。
func (*Cipher) EncryptECB ¶
EncryptECB 使用 ECB 模式加密。
参数说明:
- data:待加密的原始数据。
- padding:填充函数。
返回值:密文字节,错误信息。
func (*Cipher) EncryptGCM ¶ added in v1.22.15
EncryptGCM 使用 GCM(AEAD) 模式加密。
安全说明:
- 该模式自带完整性校验,优先级高于 CBC/CTR/CFB/OFB 等非认证模式。
- 每次加密都会随机生成 nonce,并写入密文头部,解密时自动解析。
参数说明:
- data:待加密原始数据。
- additionalData:附加认证数据,可为空;加解密两端必须完全一致。
返回值:nonce + 密文字节,错误信息。
func (*Cipher) EncryptGCMString ¶ added in v1.22.15
func (c *Cipher) EncryptGCMString(data string, encode EncodeToString, additionalData []byte) (string, error)
EncryptGCMString 使用 GCM 模式加密字符串并编码输出。
func (*Cipher) EncryptOFB ¶
EncryptOFB 使用 OFB 模式加密。
参数说明:
- data:待加密原始数据。
- padding:填充函数。
返回值:密文字节,错误信息。
type CipherOption ¶ added in v1.22.13
type CipherOption func(*cipherOptions)
CipherOption 加密器配置项。
func WithAllowUnsafeECB ¶ added in v1.22.15
func WithAllowUnsafeECB(allow bool) CipherOption
WithAllowUnsafeECB 设置是否允许使用 ECB 模式。
安全说明:
- 默认不允许,避免在生产环境中误用会泄露明文模式特征的 ECB。
- 仅在兼容旧系统密文协议时才建议显式开启。
func WithAllowUnsafeKeyIV ¶ added in v1.22.15
func WithAllowUnsafeKeyIV(allow bool) CipherOption
WithAllowUnsafeKeyIV 设置是否允许在未显式配置 IV 时退回到 key 派生 IV。
安全说明:
- 默认不允许,避免把固定且与密钥相关的 IV 当作生产默认值。
- 仅在兼容历史密文或旧系统协议时才建议显式开启。
func WithAllowUnsafeStreamMode ¶ added in v1.22.15
func WithAllowUnsafeStreamMode(allow bool) CipherOption
WithAllowUnsafeStreamMode 设置是否允许使用 CTR/CFB/OFB 等非认证流模式。
安全说明:
- 默认不允许,避免在生产环境中误用已不推荐的非认证模式。
- 仅在兼容旧系统密文协议时才建议显式开启。
func WithIV ¶ added in v1.22.13
func WithIV(iv string) CipherOption
WithIV 设置固定 IV。
IV 长度必须等于算法分组长度:AES 为 16 字节,DES/3DES 为 8 字节。
func WithRandIV ¶ added in v1.22.13
func WithRandIV(isRand bool) CipherOption
WithRandIV 设置是否随机生成 IV。
如果同时设置 WithIV,则固定 IV 优先,随机 IV 自动关闭。
type Curl ¶
type Curl struct {
Logger Logger // 日志实例
// contains filtered or unexported fields
}
Curl HTTP 请求客户端。 支持链式调用,配置丰富,功能完善:
- GET/POST/PUT/DELETE/PATCH/HEAD/OPTIONS 七种 HTTP 方法
- Header/Params/Cookie/Body 配置
- BasicAuth/Proxy/TLS 认证配置
- 请求重试/超时控制
- 请求响应日志追踪
注意:Curl 实例的请求配置阶段不是并发安全的;多个 goroutine 并发请求时,应为每个请求分别创建 Curl 实例。
使用示例:
utils.NewCurl().
SetTimeout(10).
SetHeader("Authorization", "Bearer xxx").
SetParam("page", "1").
SetBodyBytes(userData).
AfterBody(func(body []byte) error {
return json.Unmarshal(body, &result)
}).
Post("https://api.example.com/user")
func NewCurl ¶
func NewCurl(opts ...CurlOption) *Curl
New 创建一个新的 Curl 客户端实例。 默认配置:
- 超时时间:30 秒
- 最大重试:2 次
- Content-Type:application/json
- 显式传入 X-Request-Id 时立即绑定;未传入时首次发送或读取请求 ID 时自动生成
参数说明:
- opts:可选的配置项列表
返回值:配置好的 Curl 客户端指针
func (*Curl) AddCookies ¶
AddCookies 添加 Cookie 列表。 不会清空现有 Cookie,而是增量添加。
参数说明:
- cookies:可变数量的 Cookie
返回值:Curl 指针,支持链式调用
func (*Curl) AfterBody ¶ added in v1.22.13
AfterBody 请求发送后对 Response.Body 的处理回调。
参数说明:
- f:回调函数,接收 body 字节数组
返回值:Curl 指针,支持链式调用
func (*Curl) AfterBodyContext ¶ added in v1.22.17
AfterBodyContext 请求发送后对 Response.Body 的上下文处理回调。
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。
参数说明:
- f:回调函数
返回值:Curl 指针,支持链式调用
func (*Curl) AfterDoneContext ¶ added in v1.22.17
func (c *Curl) AfterDoneContext(f func(ctx context.Context, client *http.Client, request *http.Request, response *http.Response)) *Curl
AfterDoneContext 请求完成后的上下文回调。
func (*Curl) AfterResponse ¶ added in v1.22.13
AfterResponse 请求发送后的回调。
参数说明:
- f:回调函数,isDone=true 时终止后续代码执行
返回值:Curl 指针,支持链式调用
func (*Curl) AfterResponseContext ¶ added in v1.22.17
func (c *Curl) AfterResponseContext(f func(ctx context.Context, response *http.Response) (isDone bool, err error)) *Curl
AfterResponseContext 请求发送后的上下文回调。
func (*Curl) BeforeClient ¶ added in v1.22.13
BeforeClient 请求发送前的 Client 回调。
参数说明:
- f:回调函数,返回 error 时中断请求
返回值:Curl 指针,支持链式调用
func (*Curl) BeforeClientContext ¶ added in v1.22.17
BeforeClientContext 请求发送前的 Client 上下文回调。
func (*Curl) BeforeRequest ¶ added in v1.22.13
BeforeRequest 请求发送前的回调。
参数说明:
- f:回调函数,返回 error 时中断请求
返回值:Curl 指针,支持链式调用
func (*Curl) BeforeRequestContext ¶ added in v1.22.17
BeforeRequestContext 请求发送前的上下文回调。
func (*Curl) Clone ¶ added in v1.22.17
Clone 深拷贝当前 Curl 配置。 适用于以当前 Curl 为模板派生新的请求实例,避免多个 goroutine 共享可变请求状态。 Clone 会复用底层 Transport 连接池,但会复制 Header/Params/Cookie/Body 等请求级配置。
返回值:新的 Curl 指针、错误信息
func (*Curl) CloseIdleConnections ¶
func (c *Curl) CloseIdleConnections()
CloseIdleConnections 关闭所有空闲连接并释放 Transport。
func (*Curl) DelCookies ¶
DelCookies 删除指定的 Cookie。
参数说明:
- cookieName:可变数量的 Cookie 名称
返回值:Curl 指针,支持链式调用
func (*Curl) DeleteContext ¶ added in v1.22.17
DeleteContext 发起带 context 的 DELETE 请求。
func (*Curl) GetContext ¶ added in v1.22.17
GetContext 发起带 context 的 GET 请求。
func (*Curl) GetCookie ¶
GetCookie 获取指定名称的 Cookie。
参数说明:
- cookieName:Cookie 名称
返回值:*http.Cookie,不存在时返回 nil
func (*Curl) GetRequestID ¶ added in v1.22.15
GetRequestID 获取当前请求 ID。 未显式设置时会懒生成默认 ID,确保读取行为与发送请求时的链路 ID 一致。
func (*Curl) GetRequestId
deprecated
func (*Curl) GetStatusCode ¶ added in v1.22.15
GetStatusCode 获取当前允许通过校验的状态码列表副本。
返回值:状态码切片副本,调用方修改不会影响 Curl 内部状态。
func (*Curl) HeadContext ¶ added in v1.22.17
HeadContext 发起带 context 的 HEAD 请求。
func (*Curl) InsecureSkipVerify ¶
InsecureSkipVerify 设置是否跳过 HTTPS 不安全验证。 注意:生产环境禁止使用,存在安全风险。
参数说明:
- isSkip:true 跳过验证,false 进行验证
返回值:Curl 指针,支持链式调用
func (*Curl) NewRequest ¶ added in v1.22.17
NewRequest 基于当前 Curl 配置派生新的请求实例。 与 Clone 不同,NewRequest 会为新实例生成新的请求 ID,适合把当前 Curl 作为并发安全的模板复用。
返回值:新的 Curl 指针、错误信息
func (*Curl) OptionsContext ¶ added in v1.22.17
OptionsContext 发起带 context 的 OPTIONS 请求。
func (*Curl) PatchContext ¶ added in v1.22.17
PatchContext 发起带 context 的 PATCH 请求。
func (*Curl) PostContext ¶ added in v1.22.17
PostContext 发起带 context 的 POST 请求。
func (*Curl) PostFormContext ¶ added in v1.22.17
PostFormContext 发起带 context 的 POST Form 请求。
func (*Curl) PutContext ¶ added in v1.22.17
PutContext 发起带 context 的 PUT 请求。
func (*Curl) ReSetHeader ¶
ReSetHeader 重置请求头。 如果 header 为 nil,清空所有现有请求头;否则替换为新的请求头。
参数说明:
- header:新的请求头(可选)
返回值:Curl 指针,支持链式调用
func (*Curl) ReSetParams ¶
ReSetParams 重置查询参数。 如果 params 为 nil,清空所有现有参数;否则替换为新的参数。
参数说明:
- params:新的查询参数(可选)
返回值:Curl 指针,支持链式调用
func (*Curl) Send ¶
Send 发起 HTTP 请求。 封装完整请求生命周期:构建 Request、配置 Client/Transport、执行重试、处理响应。
参数说明:
- method:HTTP 方法(GET/POST/PUT/DELETE/PATCH/HEAD/OPTIONS)
- url:请求地址
- body:请求体
返回值:错误信息
func (*Curl) SendContext ¶ added in v1.22.17
SendContext 发起带 context 的 HTTP 请求。 当 ctx 被取消时,会立即中断请求以及重试等待。
func (*Curl) SetBasicAuth ¶
SetBasicAuth 设置 Basic 认证的账号及密码。
参数说明:
- username:账号
- password:密码
返回值:Curl 指针,支持链式调用
func (*Curl) SetBodyBytes ¶
SetBodyBytes 设置请求体字节。 内部会将字节数组包装为 bytes.Reader。
参数说明:
- body:字节数组
返回值:Curl 指针,支持链式调用
func (*Curl) SetContentType ¶
SetContentType 设置请求头 Content-Type。 常见类型:
- "application/x-www-form-urlencoded"
- "application/json"
- "multipart/form-data"
- "text/plain"
参数说明:
- contentType:Content-Type 值
返回值:Curl 指针,支持链式调用
func (*Curl) SetCookies ¶
SetCookies 设置 Cookie 列表。 会先清空现有 Cookie,再添加新的 Cookie。
参数说明:
- cookies:可变数量的 Cookie
返回值:Curl 指针,支持链式调用
func (*Curl) SetDefLogOutput ¶ added in v1.21.0
SetDefLogOutput 设置默认日志输出开关。 true:打印 INFO 及以下级别日志;false:禁止打印默认日志。
func (*Curl) SetDump ¶
SetDump 设置是否开启 dump 模式。 dump 模式会详细打印请求和响应的信息。
参数说明:
- dump:true 开启,false 关闭
返回值:Curl 指针,支持链式调用
func (*Curl) SetLogBodyLimit ¶ added in v1.22.17
SetLogBodyLimit 设置默认日志 body 预览长度上限。 等于 0 表示不记录 body 预览。
func (*Curl) SetMaxRetry ¶ added in v1.21.0
SetMaxRetry 设置最大请求尝试次数。 max 包含首次请求;max=0 或 max=1 表示不额外重试,最大不超过 5。
参数说明:
- max:最大请求尝试次数
返回值:Curl 指针,支持链式调用
func (*Curl) SetRequestID ¶ added in v1.22.15
SetRequestID 设置请求唯一标识。 如果未指定或为空字符串,自动生成 16 位唯一 ID。 设置后会自动更新 Logger 和 Header 中的 X-Request-Id。
func (*Curl) SetRequestId
deprecated
func (*Curl) SetStatusCode ¶
SetStatusCode 设置可接受的状态码列表。 当响应状态码不在列表中且不是 200 时,将返回错误。
参数说明:
- statusCode:可变数量的状态码
返回值:Curl 指针,支持链式调用
func (*Curl) SetUserAgent ¶
SetUserAgent 设置请求头 User-Agent。
参数说明:
- userAgent:User-Agent 字符串
返回值:Curl 指针,支持链式调用
type CurlOption ¶ added in v1.22.13
type CurlOption func(*Curl)
CurlOption Curl 配置项函数类型。 用于通过选项模式配置 Curl 客户端实例。
func WithCurlBasicAuth ¶ added in v1.22.13
func WithCurlBasicAuth(username, password string) CurlOption
WithBasicAuth 设置 BasicAuth 账号密码。
func WithCurlBodyBytes ¶ added in v1.22.13
func WithCurlBodyBytes(body []byte) CurlOption
WithBodyBytes 设置请求体字节。
func WithCurlCertKey ¶ added in v1.22.13
func WithCurlCertKey(cert, key string) CurlOption
WithCertKey 设置客户端证书和私钥。
func WithCurlContentType ¶ added in v1.22.13
func WithCurlContentType(contentType string) CurlOption
WithContentType 设置请求头 Content-Type。
func WithCurlCookies ¶ added in v1.22.13
func WithCurlCookies(cookies ...*http.Cookie) CurlOption
WithCookies 设置请求 Cookie。
func WithCurlDefLogOutput ¶ added in v1.22.13
func WithCurlDefLogOutput(enable bool) CurlOption
WithDefLogOutput 设置默认日志输出开关。
func WithCurlDump ¶ added in v1.22.13
func WithCurlDump(dump bool) CurlOption
WithDump 设置是否开启 dump 模式。
func WithCurlDumpBodyLimit ¶ added in v1.22.13
func WithCurlDumpBodyLimit(limit int64) CurlOption
WithDumpBodyLimit 设置 dump 预览内容长度上限。
func WithCurlHeader ¶ added in v1.22.13
func WithCurlHeader(key, value string) CurlOption
WithHeader 设置请求头键值。
func WithCurlHeaders ¶ added in v1.22.13
func WithCurlHeaders(headers map[string]string) CurlOption
WithHeaders 批量设置请求头。
func WithCurlInsecureSkipVerify ¶ added in v1.22.13
func WithCurlInsecureSkipVerify(isSkip bool) CurlOption
WithInsecureSkipVerify 设置是否跳过 HTTPS 验证(生产环境禁止使用)。
func WithCurlLogBodyLimit ¶ added in v1.22.17
func WithCurlLogBodyLimit(limit int64) CurlOption
WithCurlLogBodyLimit 设置默认日志 body 预览长度上限。 小于 0 的值会被忽略;等于 0 表示不记录 body 预览。
func WithCurlLogger ¶ added in v1.22.13
func WithCurlLogger(logger Logger) CurlOption
WithLogger 设置日志实例。
func WithCurlMaxRetry ¶ added in v1.22.13
func WithCurlMaxRetry(max uint8) CurlOption
WithMaxRetry 设置最大请求尝试次数。
max 包含首次请求;max=0 或 max=1 表示不额外重试,最大不超过 5。
func WithCurlParams ¶ added in v1.22.13
func WithCurlParams(params map[string]string) CurlOption
WithParams 批量设置请求参数。
func WithCurlProxyURL ¶ added in v1.22.13
func WithCurlProxyURL(proxyURL string) CurlOption
WithProxyURL 设置代理地址。
func WithCurlRequestID ¶ added in v1.22.15
func WithCurlRequestID(requestID string) CurlOption
WithCurlRequestID 设置请求 ID。
func WithCurlRequestId
deprecated
added in
v1.22.13
func WithCurlRequestId(requestId string) CurlOption
WithCurlRequestId 设置请求 ID。
Deprecated: 请使用 WithCurlRequestID。
func WithCurlRootCAs ¶ added in v1.22.13
func WithCurlRootCAs(rootCAs string) CurlOption
WithRootCAs 设置根证书路径。
func WithCurlStatusCode ¶ added in v1.22.13
func WithCurlStatusCode(statusCode ...int) CurlOption
WithStatusCode 设置可接受的状态码。
func WithCurlTimeout ¶ added in v1.22.13
func WithCurlTimeout(timeout time.Duration) CurlOption
WithTimeout 设置默认超时时间。
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 ¶
type Form struct {
// Params 表单普通字段
Params url.Values
// Files 表单文件字段(字段名 -> 文件路径列表)
Files url.Values
// MaxSingleFileSize 单个文件大小上限,单位:字节;小于等于 0 表示不限制
MaxSingleFileSize int64
// MaxTotalFileSize 所有文件总大小上限,单位:字节;小于等于 0 表示不限制
MaxTotalFileSize int64
}
Form HTTP 表单。 用于构建 multipart/form-data 类型的请求,支持文件和普通字段。
func (*Form) AddFile ¶
AddFile 对文件字段添加多个文件路径。
参数说明:
- fieldName:表单字段名
- filePath:可变数量的文件路径
返回值:Form 指针,支持链式调用
func (*Form) Reader ¶
Reader 读取 Form 内容,转换为可上传的 body 和 content-type。 如果没有文件,返回 application/x-www-form-urlencoded 格式; 如果有文件,返回 multipart/form-data 格式。
返回值:
- body:io.Reader 请求体
- contentType:Content-Type
- err:错误信息
func (*Form) SetMaxSingleFileSize ¶ added in v1.22.17
SetMaxSingleFileSize 设置单个文件大小上限。
参数说明:
- limit:单个文件大小上限,单位:字节;小于等于 0 表示不限制
返回值:Form 指针,支持链式调用
func (*Form) SetMaxTotalFileSize ¶ added in v1.22.17
SetMaxTotalFileSize 设置所有文件总大小上限。
参数说明:
- limit:所有文件总大小上限,单位:字节;小于等于 0 表示不限制
返回值: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 )
日志级别常量与 slog 默认级别保持一致。
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
}
Once 提供带重试能力的一次性执行控制器。 同一轮生命周期内只会有一个 goroutine 真正执行目标函数,其余调用方等待最终结果。
func (*Once) Do ¶ added in v1.22.13
Do 执行带重试能力的一次性调用。
参数说明:
- f:待执行函数,无参数并返回 error
- maxRetries:最大尝试次数,包含首次执行;小于等于 0 时按 1 次处理
返回值:
- error:执行成功返回 nil,最终失败返回带重试次数的错误
特性:
- 线程安全:同一时刻仅一个 goroutine 执行目标函数,其余 goroutine 等待结果
- 使用有上限的指数退避策略,避免重试间隔无限增大
- 成功或最终失败后都会缓存结果,后续调用直接复用;需重新执行时调用 Reset
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 }
Pool 是带可选重置回调的泛型对象池。
适用场景:
- 频繁复用临时对象,降低 GC 压力。
- 需要在对象归还前清理内部状态。
func NewPool ¶ added in v1.22.11
func NewPool[T any](newFn func() *T, opts ...PoolOption[T]) *Pool[T]
NewPool 创建泛型对象池。
参数说明:
- newFn:对象工厂函数;为空时回退为 `new(T)`
- opts:对象池配置项
返回值:泛型对象池指针
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 设置对象重置函数。
参数说明:
- resetFn:对象归还前的状态清理函数
type RSA ¶
type RSA struct {
// contains filtered or unexported fields
}
RSA 封装 RSA 公钥、私钥及常用加解密/签名能力。
说明:
- RSA 自身适合加密小块数据;本实现会按密钥长度自动分块,便于加密较长字符串。
- 新系统优先推荐 EncryptOAEP/DecryptOAEP;Encrypt/Decrypt(PKCS#1 v1.5) 主要用于兼容旧系统。
- RSA 对象初始化后只读,公钥/私钥可被多个 goroutine 并发用于加解密和验签。
func (*RSA) Decrypt ¶
func (r *RSA) Decrypt(encrypt string, decode DecodeString) (string, error)
Decrypt 使用私钥和 PKCS#1 v1.5 填充解密。
func (*RSA) DecryptOAEP ¶ added in v1.21.5
DecryptOAEP 使用私钥和 OAEP 填充解密。
注意:hash.Hash 实例不是并发安全对象;并发场景推荐使用 DecryptOAEPHash,由方法内部创建摘要实例。
func (*RSA) DecryptOAEPHash ¶ added in v1.22.18
func (r *RSA) DecryptOAEPHash(encrypt string, decode DecodeString, hashID crypto.Hash) (string, error)
DecryptOAEPHash 使用指定 crypto.Hash 创建独立摘要实例并执行 OAEP 解密。
该方法比直接传 hash.Hash 更适合高并发复用 RSA 对象,生产代码建议优先使用 SHA256 及以上摘要算法。
func (*RSA) Encrypt ¶
func (r *RSA) Encrypt(data string, encode EncodeToString) (string, error)
Encrypt 使用公钥和 PKCS#1 v1.5 填充加密。
生产新协议更建议使用 EncryptOAEP。
func (*RSA) EncryptOAEP ¶ added in v1.21.5
EncryptOAEP 使用公钥和 OAEP 填充加密。
注意:hash.Hash 实例不是并发安全对象;并发场景推荐使用 EncryptOAEPHash,由方法内部创建摘要实例。
func (*RSA) EncryptOAEPHash ¶ added in v1.22.18
func (r *RSA) EncryptOAEPHash(data string, encode EncodeToString, hashID crypto.Hash) (string, error)
EncryptOAEPHash 使用指定 crypto.Hash 创建独立摘要实例并执行 OAEP 加密。
该方法比直接传 hash.Hash 更适合高并发复用 RSA 对象,生产代码建议优先使用 SHA256 及以上摘要算法。
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 使用私钥生成 PSS 签名。
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 使用公钥验证 PSS 签名。
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 Replacer ¶ added in v1.22.19
type Replacer struct {
// contains filtered or unexported fields
}
Replacer 是可复用字符串替换器。
业务意图:
- 当同一批替换规则被反复使用时,调用方可复用已排序和已构建的 strings.Replacer。
- 替换规则来源于 map,构造时会固定排序,避免 map 遍历无序导致重叠替换规则结果不稳定。
func NewReplacer ¶ added in v1.22.19
NewReplacer 根据 map 规则创建可复用字符串替换器。
oldnew 字段含义:
- key:需要被替换的原字符串。
- value:替换后的目标字符串。
type Response ¶
type Response struct {
Body // JSON 响应体。
// contains filtered or unexported fields
}
Response HTTP 响应构造器。
设计目标:
- 易用:保留 Json(w).Success(...)、View(w).Text(...) 等链式调用。
- 高性能:文本写入使用 io.WriteString,文件响应使用 http.ServeContent。
- 稳定:统一管理状态码和响应头,避免重复 WriteHeader。
- 安全:文件响应禁止目录输出,下载文件名会清洗 CR/LF 等危险字符。
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) Download ¶
Download 响应下载文件。
filePath 为本地文件路径,rename 可指定下载文件名。文件名会被清洗后写入 Content-Disposition,防止 CR/LF 注入和路径穿透式文件名。
func (*Response) DownloadRequest ¶ added in v1.22.15
DownloadRequest 响应下载文件,并携带原始请求用于 Range/If-Modified-Since 等 HTTP 能力。
新代码建议在 Handler 中优先使用该方法;Download 会使用一个内部 GET 请求兜底。
func (*Response) Encode ¶
Encode 对 JSON 响应体编码。 使用默认标准库 JSON 时走手写响应包壳快路径;配置第三方 JSON 后回退到自定义编码器,避免改变调用方语义。
func (*Response) ShowRequest ¶ added in v1.22.15
ShowRequest 响应显示文件内容,并携带原始请求用于 Range/If-Modified-Since 等 HTTP 能力。
新代码建议在 Handler 中优先使用该方法;Show 会使用一个内部 GET 请求兜底。
func (*Response) StatusCode ¶
StatusCode 设置响应状态码,如 http.StatusOK。
func (*Response) Success ¶
Success 成功响应 JSON 数据。
code 为业务识别码,data 为响应数据,message 可选;未指定 message 时默认为 SUCCESS。
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。
对 text/*、application/json、application/xml 等文本类型自动追加 charset=utf-8; 对 image/*、application/octet-stream 等二进制类型保持原值,避免错误 charset。
func WithHeader ¶ added in v1.22.13
func WithHeader(f func(header http.Header)) ResponseOption
WithHeader 自定义响应头。
回调为 nil 时不做任何操作,便于条件化配置。
func WithStatusCode ¶ added in v1.22.13
func WithStatusCode(statusCode int) ResponseOption
WithStatusCode 设置响应状态码。
仅接受标准 HTTP 状态码范围 [100, 599],非法值会被忽略,避免 net/http panic。
type TrustedProxies ¶ added in v1.22.15
type TrustedProxies struct {
// contains filtered or unexported fields
}
TrustedProxies 保存可信代理 IP/CIDR 列表。 生产环境建议按网关、负载均衡或 Ingress 的固定地址显式配置,避免过宽地信任所有私网来源。
func NewTrustedProxies ¶ added in v1.22.15
func NewTrustedProxies(values ...string) (*TrustedProxies, error)
NewTrustedProxies 构造可信代理白名单。 支持传入单个 IP 或 CIDR,例如 `10.0.0.10`、`10.0.0.0/8`、`fd00::/8`。
参数说明:
- values:可信代理 IP 或 CIDR 列表
返回值:可信代理配置、错误信息
type ValidationError ¶ added in v1.22.17
type ValidationError struct {
Reason ValidationReason // 校验失败原因
Min uint8 // 最小长度约束
Max uint8 // 最大长度约束
}
ValidationError 表示结构化校验失败结果。 业务侧应通过 errors.As 提取后,根据 Target/Reason 自行决定提示文案。
func (*ValidationError) DefaultMessage ¶ added in v1.22.17
func (e *ValidationError) DefaultMessage() string
DefaultMessage 返回默认中文提示文案。 该方法适合作为兜底展示文案,也便于业务侧显式区分 Error() 与默认文案语义。
func (*ValidationError) Error ¶ added in v1.22.17
func (e *ValidationError) Error() string
Error 返回默认中文提示文案。 当业务侧未自定义提示时,该文案可以直接返回给终端用户; 如业务侧已有国际化或错误码体系,仍建议优先使用 Target/Reason 自行映射。
func (*ValidationError) MessageKey ¶ added in v1.22.17
func (e *ValidationError) MessageKey() string
MessageKey 返回稳定的文案键。 业务侧可基于该键做国际化映射、错误码映射或统一前端提示管理。
type ValidationReason ¶ added in v1.22.17
type ValidationReason string
ValidationReason 表示校验失败原因。 业务侧可根据该字段决定最终提示文案、错误码或国际化文案键。
const ( // ValidationReasonLengthOutOfRange 表示长度不在允许范围内。 ValidationReasonLengthOutOfRange ValidationReason = "length_out_of_range" // ValidationReasonInvalidFormat 表示整体格式不符合要求。 ValidationReasonInvalidFormat ValidationReason = "invalid_format" // ValidationReasonInvalidCharset 表示字符集不符合要求。 ValidationReasonInvalidCharset ValidationReason = "invalid_charset" // ValidationReasonConsecutiveUnderscore 表示存在连续下划线。 ValidationReasonConsecutiveUnderscore ValidationReason = "consecutive_underscore" // ValidationReasonMissingLowercase 表示缺少小写字母。 ValidationReasonMissingLowercase ValidationReason = "missing_lowercase" // ValidationReasonMissingUppercase 表示缺少大写字母。 ValidationReasonMissingUppercase ValidationReason = "missing_uppercase" // ValidationReasonMissingDigit 表示缺少数字。 ValidationReasonMissingDigit ValidationReason = "missing_digit" )
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 设置文件权限
Source Files
¶
- aes.go
- archive_limits.go
- base64.go
- cipher.go
- config.go
- consts.go
- curl_client.go
- curl_form.go
- curl_request.go
- curl_response.go
- curl_transport.go
- des.go
- env.go
- file.go
- gcm.go
- html.go
- ip.go
- json.go
- logger.go
- map.go
- math.go
- md5.go
- misce.go
- once.go
- padding.go
- pkcs7.go
- pool.go
- regexp.go
- response.go
- rsa.go
- runtime.go
- sha.go
- slices.go
- strconv.go
- string.go
- tar.go
- time.go
- types.go
- url.go
- zero.go
- zip.go