Documentation
¶
Overview ¶
Package utils 提供常用 Go 工具方法。
本包覆盖字符串、数字、时间、文件、归档、HTTP 请求、HTTP 响应和加密等场景。 本包也包含校验、map、slice、对象池和运行时信息等辅助能力。 安全敏感能力会在对应类型或函数注释中说明默认边界。
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 any
}
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 any
}
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 Contains[T comparable](v T, s []T) bool
- func Copy(src, dst string) error
- func Date(timeZone *time.Location, layout string, timestamp ...int64) string
- 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 FormatFileSize(size int64, decimals uint) string
- func FormatNumber(number float64, decimals uint, decPoint, thousandsSep string) string
- func GenerateKeyRSA(path string, bits int, pkcs ...bool) ([]string, error)
- func GetEnv(key string, defaultVal ...string) string
- func GetFunctionName(i any) 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 Line(r io.Reader, handle ReadLine) error
- func Local() *time.Location
- func LocalIP() string
- func MD5(str string) 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 MixStr(value string) bool
- func Mobile(value string) bool
- func MonthDay(year int, month int) (days int)
- func NoPad(data []byte, _ int) []byte
- func NoUnpad(data []byte) ([]byte, error)
- func Numeric(value string) bool
- func OctBin(data string) (string, error)
- func OctDec(str string) (int64, error)
- func OctHex(data string) (string, error)
- func PKCS7Pad(data []byte, blockSize int) []byte
- func PKCS7Unpad(data []byte) ([]byte, error)
- func ParseTime(timeZone *time.Location, parse ...string) (t time.Time, err error)
- func Password(value string, min, max uint8) error
- func Phone(value string) bool
- func ProxyURL(transport *http.Transport, proxyURL string) error
- func QQ(value string) bool
- func Rand(minInt, maxInt int64, r ...*rand.Rand) int64
- func RandomID(n int, r ...*rand.Rand) string
- func RandomLetters(n int, r ...*rand.Rand) string
- func RandomString(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 ReverseString(str string) string
- func RootCAs(config *tls.Config, rootCAs string) error
- func Round(num float64, precision int) float64
- func SHA1(str string) string
- func SHA256(str string) string
- func SHA512(str string) string
- func Scan(r io.Reader, handle ReadScan, size ...int) error
- func SecureRandomID(n int) (string, error)
- func SecureRandomLetters(n int) (string, error)
- func SecureRandomString(n int, alpha string) (string, error)
- func SecureUniqueID(l uint8) (string, error)
- func ServerIP() string
- func ServerIPContext(ctx context.Context) string
- func Size(filepath string) (int64, error)
- func StrongPassword(value string, min, max uint8) error
- func StrongPasswordWithSymbols(value string, min, max uint8) 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 TimeDetails(t time.Time) map[string]any
- 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 ToFloat64(s string) (i float64)
- func ToInt(s string) (i int)
- func ToInt64(s string) (i int64)
- 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 Unique[T comparable](s []T) []T
- func UniqueID(l uint8, r ...*rand.Rand) string
- func UniqueInPlace[T comparable](s []T) []T
- func UniqueInto[T comparable](dst, s []T) []T
- func Unmarshal(data []byte, v any) error
- func WriteFileAtomic(fileName string, data []byte, perm os.FileMode) error
- func WriteStringAtomic(fileName, data string, perm os.FileMode) error
- func ZeroPad(data []byte, blockSize int) []byte
- func ZeroUnpad(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 CipherMode, decode DecodeString, unpad Unpad) (string, error)
- func (c *Cipher) DecryptBytes(data []byte, mode CipherMode, unpad Unpad) ([]byte, error)
- func (c *Cipher) DecryptCBC(data []byte, unpad Unpad) ([]byte, error)
- func (c *Cipher) DecryptCFB(data []byte, unpad Unpad) ([]byte, error)
- func (c *Cipher) DecryptCTR(data []byte, unpad Unpad) ([]byte, error)
- func (c *Cipher) DecryptECB(data []byte, unpad Unpad) ([]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, unpad Unpad) ([]byte, error)
- func (c *Cipher) DecryptTo(dst, data []byte, mode CipherMode, unpad Unpad) ([]byte, error)
- func (c *Cipher) Encrypt(data string, mode CipherMode, encode EncodeToString, padding Pad) (string, error)
- func (c *Cipher) EncryptBytes(data []byte, mode CipherMode, padding Pad) ([]byte, error)
- func (c *Cipher) EncryptCBC(data []byte, padding Pad) ([]byte, error)
- func (c *Cipher) EncryptCFB(data []byte, padding Pad) ([]byte, error)
- func (c *Cipher) EncryptCTR(data []byte, padding Pad) ([]byte, error)
- func (c *Cipher) EncryptECB(data []byte, padding Pad) ([]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 Pad) ([]byte, error)
- func (c *Cipher) EncryptTo(dst, data []byte, mode CipherMode, padding Pad) ([]byte, error)
- type CipherBlock
- type CipherMode
- 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) Delete(url string) (err error)
- func (c *Curl) DeleteContext(ctx context.Context, url string) (err error)
- func (c *Curl) DeleteCookies(cookieName ...string) *Curl
- func (c *Curl) DeleteHeaders(keys ...string) *Curl
- func (c *Curl) DeleteParams(keys ...string) *Curl
- 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) GetHeaderValues(key string) []string
- func (c *Curl) GetParamValues(key string) []string
- func (c *Curl) GetRequestID() string
- 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) Header() http.Header
- 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) Params() url.Values
- 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) ResetHeaders(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) SetDefaultLogOutput(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) 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 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) DeleteFiles(fieldNames ...string)
- func (f *Form) DeleteParams(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 Number
- type Once
- type Option
- type Ordered
- type Pad
- 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) HTML(data string)
- func (r *Response) Header(f func(header http.Header)) *Response
- 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 Unpad
- type Unsigned
- type ValidationError
- type ValidationReason
- type WriteFile
- type WriteOption
Examples ¶
Constants ¶
const ( // Byte 表示 1 字节。 Byte int64 = 1 << (10 * iota) // KB 表示 1024 字节。 KB // MB 表示 1024 KB。 MB // GB 表示 1024 MB。 GB // TB 表示 1024 GB。 TB // PB 表示 1024 TB。 PB // EB 表示 1024 PB,int64 最大可安全表达到该级别。 EB )
const ( // YearTime 是 4 位年份格式。 YearTime = "2006" // MonthTime 是年月格式。 MonthTime = YearTime + "01" // DayTime 是年月日格式。 DayTime = MonthTime + "02" // HourTime 是年月日时格式。 HourTime = DayTime + " 15" // MinuteTime 是年月日时分格式。 MinuteTime = HourTime + "04" // SecondTime 是年月日时分秒格式。 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/Random* 函数使用。
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(纳秒)。 使用 + 或 - 前缀表示增加或减少。
例如:
AddTime(t, "-1D", "+2H", "30S") // 减1天,加2小时,加30秒
func Certificate ¶
Certificate 设置客户端证书。
func ClientIP ¶
ClientIP 获取客户端 IP 地址。 默认仅在请求来自回环地址时信任转发头,生产环境建议使用 ClientIPWithTrustedProxies 显式配置白名单。
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`。
func Contains ¶ added in v1.22.20
func Contains[T comparable](v T, s []T) bool
Contains 检查 s 中是否存在 v。1.21 版本以上推荐使用标准库 slices.Contains(s, v)。
func Date ¶
Date 使用 patterns 规则格式化时间。 patterns 支持 PHP 风格的格式化符(如 Y-m-d H:i:s)。
例如:
Date(CST(), "Y-m-d H:i:s", 1700000000) // "2023-11-15 01:46:40"
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 内容并恢复原始流。
func FormatFileSize ¶ added in v1.22.20
FormatFileSize 将字节数格式化为易读的文件大小。
size 文件实际大小(Byte) decimals 保留几位小数
func FormatNumber ¶ added in v1.22.20
FormatNumber 以千位分隔符方式格式化数字。
number 要格式化的数字 decimals 保留几位小数 decPoint 小数点[.] thousandsSep 千位分隔符[,]
func GenerateKeyRSA ¶
GenerateKeyRSA 生成 RSA 密钥文件。
path 为密钥存放目录;bits 为密钥位数;生产环境要求至少 2048。 pkcs[0] 控制公钥格式是否为 PKCS8,默认 true;pkcs[1] 控制私钥格式是否为 PKCS1,默认 true。
func GetFunctionName ¶ added in v1.22.12
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 MD5 ¶ added in v1.22.20
MD5 返回字符串的 MD5 十六进制摘要。
安全说明:MD5 已不适合密码存储、签名、完整性安全校验等安全场景; 该函数仅用于历史协议兼容或非安全哈希标识。
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 NoPad ¶ added in v1.22.20
NoPad 表示不做任何填充,适合 CTR/CFB/OFB/GCM 等流式或 AEAD 模式。 返回值会复制原始数据,避免调用方后续修改原切片影响加密流程。
func NoUnpad ¶ added in v1.22.20
NoUnpad 表示不做任何去填充,适合 CTR/CFB/OFB/GCM 等流式或 AEAD 模式。 返回值会复制原始数据,避免调用方后续修改结果影响后续处理。
func PKCS7Pad ¶ added in v1.22.20
PKCS7Pad 按 PKCS#7 规则填充数据。
返回值总是新切片,避免 append 复用调用方底层数组导致原始数据被意外修改。
func ParseTime ¶ added in v1.22.20
ParseTime 解析时间字符串(智能解析)。 支持多种常见格式自动识别,也支持指定格式解析。
例如:
ParseTime(CST(), "2006-01-02 15:04:05") // 当前时间(如果解析失败) ParseTime(CST(), "2006-01-02 15:04:05", "2024-01-01 12:00:00") // 指定时间 ParseTime(CST(), "Y-m-d H:i:s") // 当前时间
func RandomID ¶ added in v1.22.20
RandomID 随机生成字符串,使用 ALNUM 规则。 为兼容旧行为,首字符固定从 ALPHA 中选择,避免数字开头。 注意:该函数基于 math/rand,仅适用于测试数据、临时标识等非安全场景。 禁止用于 token、验证码、重置链接、签名密钥等安全敏感用途;安全场景请使用 SecureRandomID。
n 生成字符串长度 r 随机种子 rand.NewSource(time.Now().UnixNano()) : 批量生成时传入r参数可提升生成随机数效率
func RandomLetters ¶ added in v1.22.20
RandomLetters 随机生成字符串,使用 ALPHA 规则。 注意:该函数基于 math/rand,仅适用于测试数据、临时标识等非安全场景。 禁止用于 token、验证码、重置链接、签名密钥等安全敏感用途;安全场景请使用 SecureRandomLetters。
n 生成字符串长度 r 随机种子 rand.NewSource(time.Now().UnixNano()) : 批量生成时传入r参数可提升生成随机数效率
func RandomString ¶ added in v1.22.20
RandomString 随机生成字符串。 注意:该函数基于 math/rand,仅适用于测试数据、临时标识等非安全场景。 禁止用于 token、验证码、重置链接、签名密钥等安全敏感用途;安全场景请使用 SecureRandomString。
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 ¶
package main
import (
"net/http"
"github.com/Is999/go-utils"
)
func main() {
mux := http.NewServeMux()
registerRedirectExample(mux)
}
func registerRedirectExample(mux *http.ServeMux) {
mux.HandleFunc("/response/redirect", func(w http.ResponseWriter, r *http.Request) {
utils.Redirect(w, "/response/json")
})
}
Output:
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 SHA1 ¶ added in v1.22.20
SHA1 返回字符串的 SHA-1 十六进制摘要。
安全说明:SHA-1 已不适合签名、证书、密码存储等安全场景; 该函数仅用于历史协议兼容或非安全哈希标识。
func SHA256 ¶ added in v1.22.20
SHA256 返回字符串的 SHA-256 十六进制摘要。 适合普通摘要场景;密码存储仍应使用 bcrypt/argon2/scrypt 等专用算法。
func SHA512 ¶ added in v1.22.20
SHA512 返回字符串的 SHA-512 十六进制摘要。 适合普通摘要场景;密码存储仍应使用 bcrypt/argon2/scrypt 等专用算法。
func SecureRandomID ¶ added in v1.22.20
SecureRandomID 使用密码学安全随机源生成字符串,使用 ALNUM 规则。 为兼容历史命名习惯,首字符固定从 ALPHA 中选择,避免数字开头。
func SecureRandomLetters ¶ added in v1.22.20
SecureRandomLetters 使用密码学安全随机源生成字符串,使用 ALPHA 规则。
func SecureRandomString ¶ added in v1.22.20
SecureRandomString 使用密码学安全随机源按自定义字符集生成字符串。
func SecureUniqueID ¶ added in v1.22.20
SecureUniqueID 使用密码学安全随机源生成长度范围 16-32 位的字符串标识。 与 UniqueID 不同,SecureUniqueID 不依赖时间戳,不保证可排序。
func ServerIP ¶
func ServerIP() string
ServerIP 获取服务器对外 IP 地址。 默认优先返回缓存值或本地网卡 IP,避免在热路径上频繁拨号外网地址。 如需自定义超时控制,可使用 ServerIPContext。
func ServerIPContext ¶ added in v1.22.17
ServerIPContext 获取服务器出站 IP 地址,并允许调用方控制超时。 默认优先返回缓存值或本地网卡 IP,仅在本地 IP 不可用时才回退到 UDP 探测。
func StrongPassword ¶ added in v1.22.20
StrongPassword 强密码(必须包含大小写字母和数字的组合,不能使用特殊字符,长度在min-max之间)
func StrongPasswordWithSymbols ¶ added in v1.22.20
StrongPasswordWithSymbols 强密码(必须包含大小写字母和数字的组合,可以使用特殊字符,长度在min-max之间)
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 TimeDetails ¶ added in v1.22.20
TimeDetails 获取时间的详细信息映射表。
返回值字段说明:
- 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 TimeFormat ¶
TimeFormat 将时间戳格式化为字符串。
例如:
TimeFormat(CST(), "2006-01-02 15:04:05", 1700000000) TimeFormat(CST(), "2006-01-02 15:04:05", 1700000000000000000) // 纳秒时间戳
func Unique ¶ added in v1.22.0
func Unique[T comparable](s []T) []T
Unique 去除 s 中重复的值。 返回结果保持首个元素出现顺序;返回切片使用新的底层数组,避免调用方误改原始数据。
func UniqueID ¶ added in v1.22.20
UniqueID 生成一个长度范围 16-32 位的唯一 ID 字符串(可排序字符串)。 UniqueID 只生成字符串标识,不承诺全局强唯一;强唯一场景建议使用业务唯一键或 UUID/ULID。 注意:该函数基于时间戳与 math/rand,仅适用于非安全场景。 禁止用于 token、验证码、重置链接等安全敏感用途;安全场景请使用 SecureUniqueID。
l 生成 UniqueID 长度: 取值范围[16-32], 小于16按16位处理, 大于32按32位处理 r 随机种子 rand.NewSource(time.Now().UnixNano()) : 批量生成时传入r参数可提升生成随机数效率
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 截断目标文件。
func WriteStringAtomic ¶ added in v1.22.17
WriteStringAtomic 原子写入完整字符串内容。 适用于希望以字符串形式原子覆盖目标文件的场景。
func ZeroPad ¶ added in v1.22.20
ZeroPad 使用 0 字节填充到分组大小的整数倍。
注意:ZeroPad 无法区分明文末尾真实的 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 语义和 `NoPad/NoUnpad` 零额外拷贝路径。
func DES ¶
func DES(key string, opts ...CipherOption) (*Cipher, error)
DES 创建 DES/3DES 分组密码封装。
安全说明:DES 密钥空间过小,3DES 也属于历史兼容算法;新系统应优先使用 AES-GCM。 当 key 长度为 24 字节时自动使用 3DES,长度为 8 字节时使用 DES。
key 秘钥
func NewCipher ¶
func NewCipher(key string, block CipherBlock, opts ...CipherOption) (*Cipher, error)
NewCipher 创建通用分组加密器。
key 为原始密钥字符串;block 通常传 aes.NewCipher、des.NewCipher 或 des.NewTripleDESCipher。
func TripleDES ¶ added in v1.22.20
func TripleDES(key string, opts ...CipherOption) (*Cipher, error)
TripleDES 创建 3DES 分组密码封装。
安全说明:3DES 仅用于旧协议兼容,新系统应优先使用 AES-GCM。
key 秘钥
func (*Cipher) Decrypt ¶
func (c *Cipher) Decrypt(encrypt string, mode CipherMode, decode DecodeString, unpad Unpad) (string, error)
Decrypt 解密编码后的密文字符串。
encrypt 为待解密数据;decode 为解码方法;unpad 为去填充方法。
func (*Cipher) DecryptBytes ¶ added in v1.22.15
DecryptBytes 解密原始密文字节。
func (*Cipher) DecryptCBC ¶
DecryptCBC 使用 CBC 模式解密。
func (*Cipher) DecryptCFB ¶
DecryptCFB 使用 CFB 模式解密。
func (*Cipher) DecryptCTR ¶
DecryptCTR 使用 CTR 模式解密。
func (*Cipher) DecryptECB ¶
DecryptECB 使用 ECB 模式解密。
func (*Cipher) DecryptGCM ¶ added in v1.22.15
DecryptGCM 使用 GCM(AEAD) 模式解密。
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 模式解密。
func (*Cipher) DecryptTo ¶ added in v1.22.19
DecryptTo 将解密结果追加到 dst 并返回结果切片。 高频解密场景可复用调用方缓冲区,减少明文字节切片分配;CTR/CFB/OFB 且 NoUnpad 时走直接写入快路径。
func (*Cipher) Encrypt ¶
func (c *Cipher) Encrypt(data string, mode CipherMode, encode EncodeToString, padding Pad) (string, error)
Encrypt 加密字符串并编码输出。
data 为待加密数据;mode 为加密模式;encode 为编码方法;padding 为填充方法。
func (*Cipher) EncryptBytes ¶ added in v1.22.15
EncryptBytes 加密字节数据并返回原始密文字节。
该方法适合业务层自行选择编码方式,可避免 string 与 []byte 的额外转换。
func (*Cipher) EncryptCBC ¶
EncryptCBC 使用 CBC 模式加密。
func (*Cipher) EncryptCFB ¶
EncryptCFB 使用 CFB 模式加密。
func (*Cipher) EncryptCTR ¶
EncryptCTR 使用 CTR 模式加密。
func (*Cipher) EncryptECB ¶
EncryptECB 使用 ECB 模式加密。
func (*Cipher) EncryptGCM ¶ added in v1.22.15
EncryptGCM 使用 GCM(AEAD) 模式加密。
安全说明:
- 该模式自带完整性校验,优先级高于 CBC/CTR/CFB/OFB 等非认证模式。
- 每次加密都会随机生成 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 模式加密。
type CipherMode ¶ added in v1.22.20
type CipherMode int8
CipherMode 密码模式
const ( // ECB 表示电码本模式,无须设置初始化向量 IV。 ECB CipherMode = iota // CBC 表示密码分组链接模式,明文长度不是分组长度整数倍时需要填充。 CBC // CTR 表示计数器模式。 CTR // CFB 表示密码反馈模式。 CFB // OFB 表示输出反馈模式。 OFB )
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
NewCurl 创建一个新的 Curl 客户端实例。 默认配置:
- 超时时间:30 秒
- 最大重试:2 次
- Content-Type:application/json
- 显式传入 X-Request-Id 时立即绑定;未传入时首次发送或读取请求 ID 时自动生成
func (*Curl) AddCookies ¶
AddCookies 添加 Cookie 列表。 不会清空现有 Cookie,而是增量添加。
func (*Curl) AddHeaders ¶
AddHeaders 批量添加请求头值。
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。
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 请求发送后的回调。
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 回调。
func (*Curl) BeforeClientContext ¶ added in v1.22.17
BeforeClientContext 请求发送前的 Client 上下文回调。
func (*Curl) BeforeRequest ¶ added in v1.22.13
BeforeRequest 请求发送前的回调。
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 等请求级配置。
func (*Curl) CloseIdleConnections ¶
func (c *Curl) CloseIdleConnections()
CloseIdleConnections 关闭所有空闲连接并释放 Transport。
func (*Curl) DeleteContext ¶ added in v1.22.17
DeleteContext 发起带 context 的 DELETE 请求。
func (*Curl) DeleteCookies ¶ added in v1.22.20
DeleteCookies 删除指定的 Cookie。
func (*Curl) DeleteHeaders ¶ added in v1.22.20
DeleteHeaders 删除指定的请求头。
func (*Curl) DeleteParams ¶ added in v1.22.20
DeleteParams 删除指定的查询参数。
func (*Curl) GetContext ¶ added in v1.22.17
GetContext 发起带 context 的 GET 请求。
func (*Curl) GetHeaderValues ¶
GetHeaderValues 获取请求头中指定键的所有值。
func (*Curl) GetParamValues ¶
GetParamValues 获取查询参数中指定键的值。
func (*Curl) GetRequestID ¶ added in v1.22.15
GetRequestID 获取当前请求 ID。 未显式设置时会懒生成默认 ID,确保读取行为与发送请求时的链路 ID 一致。
func (*Curl) GetStatusCode ¶ added in v1.22.15
GetStatusCode 获取当前允许通过校验的状态码列表副本。
func (*Curl) HeadContext ¶ added in v1.22.17
HeadContext 发起带 context 的 HEAD 请求。
func (*Curl) InsecureSkipVerify ¶
InsecureSkipVerify 设置是否跳过 HTTPS 不安全验证。 注意:生产环境禁止使用,存在安全风险。
func (*Curl) NewRequest ¶ added in v1.22.17
NewRequest 基于当前 Curl 配置派生新的请求实例。 与 Clone 不同,NewRequest 会为新实例生成新的请求 ID,适合把当前 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) ResetHeaders ¶ added in v1.22.20
ResetHeaders 重置请求头。 如果 header 为 nil,清空所有现有请求头;否则替换为新的请求头。
func (*Curl) ResetParams ¶ added in v1.22.20
ResetParams 重置查询参数。 如果 params 为 nil,清空所有现有参数;否则替换为新的参数。
func (*Curl) SendContext ¶ added in v1.22.17
SendContext 发起带 context 的 HTTP 请求。 当 ctx 被取消时,会立即中断请求以及重试等待。
func (*Curl) SetBasicAuth ¶
SetBasicAuth 设置 Basic 认证的账号及密码。
func (*Curl) SetBodyBytes ¶
SetBodyBytes 设置请求体字节。 内部会将字节数组包装为 bytes.Reader。
func (*Curl) SetContentType ¶
SetContentType 设置请求头 Content-Type。 常见类型:
- "application/x-www-form-urlencoded"
- "application/json"
- "multipart/form-data"
- "text/plain"
func (*Curl) SetCookies ¶
SetCookies 设置 Cookie 列表。 会先清空现有 Cookie,再添加新的 Cookie。
func (*Curl) SetDefaultLogOutput ¶ added in v1.22.20
SetDefaultLogOutput 设置默认日志输出开关。 true:打印 INFO 及以下级别日志;false:禁止打印默认日志。
func (*Curl) SetHeaders ¶
SetHeaders 批量设置请求头。
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。
func (*Curl) SetRequestID ¶ added in v1.22.15
SetRequestID 设置请求唯一标识。 如果未指定或为空字符串,自动生成 16 位唯一 ID。 设置后会自动更新 Logger 和 Header 中的 X-Request-Id。
func (*Curl) SetStatusCode ¶
SetStatusCode 设置可接受的状态码列表。 当响应状态码不在列表中且不是 200 时,将返回错误。
func (*Curl) SetUserAgent ¶
SetUserAgent 设置请求头 User-Agent。
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
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 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
WithCurlLogger 设置日志实例。
func WithCurlMaxRetry ¶ added in v1.22.13
func WithCurlMaxRetry(max uint8) CurlOption
WithCurlMaxRetry 设置最大请求尝试次数。
max 包含首次请求;max=0 或 max=1 表示不额外重试,最大不超过 5。
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.15
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 ¶
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) DeleteFiles ¶ added in v1.22.20
DeleteFiles 删除指定的文件字段。
func (*Form) DeleteParams ¶ added in v1.22.20
DeleteParams 删除指定的表单字段。
func (*Form) Reader ¶
Reader 读取 Form 内容,转换为可上传的 body 和 content-type。 如果没有文件,返回 application/x-www-form-urlencoded 格式; 如果有文件,返回 multipart/form-data 格式。
func (*Form) SetMaxSingleFileSize ¶ added in v1.22.17
SetMaxSingleFileSize 设置单个文件大小上限。
func (*Form) SetMaxTotalFileSize ¶ added in v1.22.17
SetMaxTotalFileSize 设置所有文件总大小上限。
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) 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 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 创建泛型对象池。
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
}
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.20
func JSON(w http.ResponseWriter, opts ...ResponseOption) *Response
JSON 创建 JSON 响应构造器。
Example ¶
package main
import (
"net/http"
"github.com/Is999/go-utils"
)
type User struct {
Name string `json:"name" xml:"name"`
Age int `json:"age" xml:"age"`
Sex string `json:"sex" xml:"sex"`
IsMarried bool `json:"is_married" xml:"isMarried"`
Address string `json:"address" xml:"address"`
phone string
}
func main() {
mux := http.NewServeMux()
registerJSONExample(mux)
}
func registerJSONExample(mux *http.ServeMux) {
mux.HandleFunc("/response/json", func(w http.ResponseWriter, r *http.Request) {
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)
})
}
Output:
func View ¶
func View(w http.ResponseWriter, opts ...ResponseOption) *Response
View 创建文本/文件响应构造器。
Example ¶
package main
import (
"net/http"
"github.com/Is999/go-utils"
)
type User struct {
Name string `json:"name" xml:"name"`
Age int `json:"age" xml:"age"`
Sex string `json:"sex" xml:"sex"`
IsMarried bool `json:"is_married" xml:"isMarried"`
Address string `json:"address" xml:"address"`
phone string
}
func main() {
mux := http.NewServeMux()
registerViewExample(mux)
}
func registerViewExample(mux *http.ServeMux) {
mux.HandleFunc("/response/html", func(w http.ResponseWriter, r *http.Request) {
utils.View(w).HTML("<p>这是一个<b style=\"color: red\">段落!</b></p>")
})
mux.HandleFunc("/response/xml", func(w http.ResponseWriter, r *http.Request) {
user := User{
Name: "张三",
Age: 22,
Sex: "男",
IsMarried: false,
Address: "北京市",
phone: "131188889999",
}
utils.View(w).XML(user)
})
mux.HandleFunc("/response/text", func(w http.ResponseWriter, r *http.Request) {
utils.View(w).Text("<p>这是一个<b style=\"color: red\">段落!</b></p>")
})
mux.HandleFunc("/response/show", func(w http.ResponseWriter, r *http.Request) {
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)
})
mux.HandleFunc("/response/download", func(w http.ResponseWriter, r *http.Request) {
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)
})
}
Output:
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`。
type ValidationError ¶ added in v1.22.17
type ValidationError struct {
Reason ValidationReason // 校验失败原因
Min uint8 // 最小长度约束
Max uint8 // 最大长度约束
}
ValidationError 表示结构化校验失败结果。 业务侧应通过 errors.As 提取后,根据 Reason 自行决定提示文案。
func (*ValidationError) DefaultMessage ¶ added in v1.22.17
func (e *ValidationError) DefaultMessage() string
DefaultMessage 返回默认中文提示文案。
func (*ValidationError) Error ¶ added in v1.22.17
func (e *ValidationError) Error() string
Error 返回默认中文提示文案。 当业务侧未自定义提示时,该文案可以直接返回给终端用户; 如业务侧已有国际化或错误码体系,仍建议优先使用 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
- doc.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