### Install ZLSGo using Go Get Source: https://github.com/sohaha/zlsgo/blob/master/docs/README.md This command installs the ZLSGo library using the Go package manager. It fetches the latest version of the library and makes it available for use in your Go projects. ```bash go get github.com/sohaha/zlsgo ``` -------------------------------- ### Get Request Information (Go) Source: https://github.com/sohaha/zlsgo/blob/master/docs/znet.md These methods provide access to key details of the incoming HTTP request, including the URL, path, method, and client IP address. They are essential for routing and request processing logic. ```Go // 获取请求URL func (c *Context) URL() *url.URL // 获取请求路径 func (c *Context) Path() string // 获取请求方法 func (c *Context) Method() string // 获取客户端IP地址 func (c *Context) GetClientIP() string ``` -------------------------------- ### Context Management and Control Flow (Go) Source: https://github.com/sohaha/zlsgo/blob/master/docs/znet.md Functions for controlling the middleware chain and managing context values. `Next()` passes control to the next middleware, while `MustGet()` and `Get()` retrieve values, with `MustGet()` panicking if the key is not found. `Set()` stores values in the context. ```Go // 执行下一个中间件 func (c *Context) Next() // 获取上下文值,如果不存在则panic func (c *Context) MustGet(key string) interface{} // 获取上下文值 func (c *Context) Get(key string) (interface{}, bool) // 设置上下文值 func (c *Context) Set(key string, value interface{}) ``` -------------------------------- ### Go: Cross-Platform Process and Bash Execution Source: https://github.com/sohaha/zlsgo/blob/master/docs/zshell.md Includes functions for cross-platform process management and specifically for running commands within a bash shell. `RunNewProcess` starts a new process and returns its PID, while `RunBash` executes a given command string within a bash environment, providing output and error details. ```go func RunNewProcess(file string, args []string) (pid int, err error) func RunBash(ctx context.Context, command string) (code int, outStr, errStr string, err error) ``` -------------------------------- ### Go: ztype 模块映射操作与能力 Source: https://github.com/sohaha/zlsgo/blob/master/docs/ztype.md 此代码段展示了 ztype 模块中用于处理映射类型的方法和类型定义。Map() 和 Maps() 用于将输入转换为映射类型。Map 类型提供了 DeepCopy, Get, Set, Has, Delete, Valid, Keys, ForEach, IsEmpty 等常用功能。 ```go package ztype // Map 转换为映射类型 func (t Type) Map() Map // Maps 转换为映射切片 func (t Type) Maps() Maps type Map map[string]interface{} ``` ```go package ztype // Map 类型能力: DeepCopy, Get, Set, Has, Delete, Valid, Keys, ForEach, IsEmpty ``` -------------------------------- ### Response Manipulation and Host Information (Go) Source: https://github.com/sohaha/zlsgo/blob/master/docs/znet.md Functions for setting response headers, retrieving the completion link, and getting the host name. `SetHeader()` is used to add or modify response headers, while `CompletionLink()` and `Host()` provide specific string values. ```Go // 设置响应头 func (c *Context) SetHeader(key, value string) // 获取完成链接 func (c *Context) CompletionLink() string // 获取主机名 func (c *Context) Host() string ``` -------------------------------- ### Go: Sorted Map Implementation Source: https://github.com/sohaha/zlsgo/blob/master/docs/zarray.md Implementation of a sorted map in Go that maintains the insertion order of keys. Provides methods for setting, getting, checking existence, deleting keys, retrieving length, listing keys in order, and iterating over key-value pairs. ```go import "github.com/sohaha/zlsgo/zarray" // Create a new sorted map // K must be comparable, V can be any type sortedMap := zarray.NewSortMap[string, int]() // Set key-value pairs sortedMap.Set("apple", 1) sortedMap.Set("banana", 2) sortedMap.Set("cherry", 3) // Get a value by key value, ok := sortedMap.Get("banana") // Check if a key exists hasKey := sortedMap.Has("apple") // Delete keys sortedMap.Delete("banana") // Get the number of elements length := sortedMap.Len() // Get keys in insertion order keys := sortedMap.Keys() // Iterate over key-value pairs sortedMap.ForEach(func(key string, value int) bool { // Process key and value return true // return false to stop iteration }) ``` -------------------------------- ### Dynamically Call Methods Based on Name Prefix in Go Source: https://github.com/sohaha/zlsgo/blob/master/docs/zreflect.md Shows how to dynamically invoke methods on an object using zreflect.RunAssignMethod. A callback function is provided to filter method names, allowing for conditional execution. In this example, only methods starting with 'Get' are invoked, passing arbitrary arguments. ```go err := zreflect.RunAssignMethod(obj, func(methodName string) bool { // 只调用以 "Get" 开头的方法 return strings.HasPrefix(methodName, "Get") }, arg1, arg2) ``` -------------------------------- ### Go: zcli 示例 - 基本命令结构 Source: https://github.com/sohaha/zlsgo/blob/master/docs/zcli.md 演示如何定义一个简单的命令行命令,包括命令结构体、标志设置和命令执行逻辑。通过 `zcli.Add` 添加命令,并通过 `zcli.Start` 启动 CLI。 ```go package main import ( "fmt" "github.com/sohaha/zlsgo/zcli" ) // 定义命令结构体 type testCmd struct{} func (cmd *testCmd) Flags(sub *zcli.Subcommand) { // 设置命令标志 sub.SetVar("name", "测试名称").String("default") sub.SetVar("count", "测试次数").Int(1) } func (cmd *testCmd) Run(args []string) { fmt.Println("执行测试命令") fmt.Printf("参数: %v\n", args) } func main() { // 添加命令 zcli.Add("test", "测试命令", &testCmd{}) // 设置未知命令处理 zcli.SetUnknownCommand(func(cmd string) { fmt.Printf("未知命令: %s\n", cmd) zcli.Help() }) // 启动 CLI zcli.Start() } ``` -------------------------------- ### Go: zcli 服务管理函数 Source: https://github.com/sohaha/zlsgo/blob/master/docs/zcli.md 用于启动和管理后台服务。`LaunchServiceRun` 用于直接运行服务,`LaunchService` 返回服务接口,`GetService` 用于获取已启动的服务。 ```go // 启动服务运行 func LaunchServiceRun(name string, description string, fn func(), config ...*daemon.Config) error // 启动服务 func LaunchService(name string, description string, fn func(), config ...*daemon.Config) (daemon.ServiceIface, error) // 获取服务 func GetService() (daemon.ServiceIface, error) ``` -------------------------------- ### Go: Time Conversion and Utilities Source: https://github.com/sohaha/zlsgo/blob/master/docs/ztime.md This section provides utility functions for time conversion, including a context-aware sleep function, getting the day of the week, and calculating the start and end timestamps for a given month and year. ```go // Sleep with context func Sleep(ctx context.Context, duration time.Duration) error // Get the day of the week (integer representation) func Week(t time.Time) int // Get the month range (start and end Unix timestamps) func MonthRange(year, month int) (beginTime, endTime int64, err error) ``` -------------------------------- ### Go: zcli 后台服务启动示例 Source: https://github.com/sohaha/zlsgo/blob/master/docs/zcli.md 演示如何使用 `zcli.LaunchService` 函数启动一个后台服务。该函数接收服务名称、描述和执行函数,并可配置服务参数。 ```go // 启动后台服务 err := zcli.LaunchService("myapp", "我的应用", func() { // 服务逻辑 for { // 服务循环 } }) ``` -------------------------------- ### Go: Concurrent-Safe Hash Map Source: https://github.com/sohaha/zlsgo/blob/master/docs/zarray.md A concurrent-safe generic hash map implementation in Go. Offers methods for setting, getting, getting or setting, retrieving and deleting, providing values, deleting keys, checking existence, getting length, ranging over pairs, clearing, swapping values, and compare-and-swap operations. ```go import "github.com/sohaha/zlsgo/zarray" // Create a new concurrent-safe hash map // K must be hashable, V can be any type hashMap := zarray.NewHashMap[string, int]() // Set key-value pairs hashMap.Set("one", 1) hashMap.Set("two", 2) // Get a value by key value, ok := hashMap.Get("one") // Get or set a value if the key doesn't exist actual, loaded := hashMap.GetOrSet("three", 3) // Get and delete a key-value pair deletedValue, deletedOk := hashMap.GetAndDelete("two") // Provide a value using a function if the key doesn't exist actualVal, loadedVal, computedVal := hashMap.ProvideGet("four", func() (int, bool) { return 4, true }) // Delete keys hashMap.Delete("one", "three") // Check if a key exists hasKey := hashMap.Has("one") // Get the number of elements length := hashMap.Len() // Iterate over key-value pairs hashMap.Range(func(key string, value int) bool { // Process key and value return true // return false to stop iteration }) // Clear the map hashMap.Clear() // Swap a value for a key oldValue, swapped := hashMap.Swap("four", 44) // Compare and swap a value casSuccess := hashMap.CAS("four", 4, 444) ``` -------------------------------- ### Go: Create and Clean zlog Logger Instances Source: https://github.com/sohaha/zlsgo/blob/master/docs/zlog.md Functions for creating new logger instances with optional module names, initializing zlog with custom settings, and cleaning up logger resources. These are fundamental for setting up logging within an application. ```go func New(moduleName ...string) *Logger func NewZLog(out io.Writer, prefix string, flag int, level int, color bool, calldDepth int) *Logger func CleanLog(log *Logger) ``` -------------------------------- ### Go: Get Directory Size and File Count Source: https://github.com/sohaha/zlsgo/blob/master/docs/zfile.md This Go code snippet shows how to get the total size and file count of a directory using the `zfile.StatDir` function. It requires a valid directory path as input and returns the size, total file count, and any potential error encountered. ```go // 统计目录 size, total, err := zfile.StatDir(path) ``` -------------------------------- ### Go: ztype 模块通过路径表达式访问嵌套值 Source: https://github.com/sohaha/zlsgo/blob/master/docs/ztype.md 此代码段展示了 ztype 模块中 `Type` 接口的 `Get` 方法,它允许使用路径表达式安全地访问嵌套数据结构中的值。这对于处理复杂的 JSON 或嵌套映射非常有用。 ```go package ztype // Get 使用路径表达式获取嵌套值 func (t Type) Get(path string) Type ``` -------------------------------- ### Go: zcli 命令行解析函数 Source: https://github.com/sohaha/zlsgo/blob/master/docs/zcli.md 提供命令行参数和标志的解析、获取以及命令的添加和运行。支持设置未知命令处理函数,并能获取当前的命令行参数和标志集合。 ```go // 添加命令到CLI系统 func Add(name, description string, command Cmd) *cmdCont // 获取指定名称的命令 func GetCommand(name string) (cmd *cmdCont, ok bool) // 获取所有命令 func GetAllCommand() map[string]*cmdCont // 设置未知命令处理函数 func SetUnknownCommand(fn func(string)) // 解析命令行参数 func Parse(arg ...[]string) bool // 获取命令行参数 func Args() []string // 获取标志集合 func Flag() *flag.FlagSet // 获取标志集合(别名) func GetFlag() *flag.FlagSet // 运行命令 func Run(runFunc ...runFunc) bool // 启动CLI系统 func Start(runFunc ...runFunc) // 停止CLI系统 func Stop() // 等待CLI完成 func Wait() // 致命错误处理 func Fatal(format string, v ...interface{}) ``` -------------------------------- ### 集成 zlsgo pprof 到标准库 http.Server (Go) Source: https://github.com/sohaha/zlsgo/blob/master/docs/zpprof.md 将 zlsgo 的 pprof 引擎集成到 Go 标准库的 http.Server 中,允许在标准 HTTP 服务器上暴露 pprof 相关的路由。这需要创建一个 znet 引擎来注册 pprof,然后将其路由添加到 Go 的 http.ServeMux 中。 ```go package main import ( "fmt" "net/http" "github.com/sohaha/zlsgo/zpprof" "github.com/sohaha/zlsgo/znet" ) func main() { // 创建 znet 引擎用于 pprof pprofEngine := znet.New() zpprof.Register(pprofEngine, "debug-token") // 创建标准库服务器 mux := http.NewServeMux() // 添加业务路由 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello World")) }) // 将 pprof 路由添加到标准库服务器 for _, route := range pprofEngine.Routes() { mux.HandleFunc(route.Path, func(w http.ResponseWriter, r *http.Request) { // 处理 pprof 请求 }) } // 启动服务器 fmt.Println("服务器启动在 :8080") http.ListenAndServe(":8080", mux) } ``` -------------------------------- ### Get Request Body in Different Formats (Go) Source: https://github.com/sohaha/zlsgo/blob/master/docs/znet.md These functions retrieve the raw request body as a reader, string, or byte slice. They are fundamental for accessing incoming request data before specific parsing. ```Go // 获取请求体(Reader) func (c *Context) BodyReader() io.Reader // 获取请求体(字符串) func (c *Context) BodyString() string // 获取请求体 func (c *Context) Body() []byte ``` -------------------------------- ### Go: zcli 命令接口定义 Source: https://github.com/sohaha/zlsgo/blob/master/docs/zcli.md 定义了 `Cmd` 接口,所有自定义命令都必须实现此接口。接口包含 `Flags` 方法用于设置命令标志,以及 `Run` 方法用于执行命令逻辑。 ```go type Cmd interface { Flags(sub *Subcommand) Run(args []string) } ``` -------------------------------- ### Basic Usage of ZLSGo String and Array Modules Source: https://github.com/sohaha/zlsgo/blob/master/docs/README.md This Go code snippet demonstrates the basic usage of the zstring and zarray modules from the ZLSGo library. It shows how to capitalize the first letter of a string and how to create and manipulate an array. ```go package main import ( "fmt" "github.com/sohaha/zlsgo/zstring" "github.com/sohaha/zlsgo/zarray" ) func main() { // 字符串处理 result := zstring.Ucfirst("hello world") fmt.Println(result) // "Hello world" // 数组操作 arr := zarray.NewArray(5) arr.Push("张三", "李四", "王五") fmt.Printf("数组长度: %d\n", arr.Length()) } ``` -------------------------------- ### Go: zcli 工具函数 Source: https://github.com/sohaha/zlsgo/blob/master/docs/zcli.md 提供一系列实用的工具函数,包括获取用户输入、检查运行环境、错误处理、显示帮助和错误信息等。 ```go // 获取用户输入 func Input(problem string, required bool) string // 获取用户输入(换行) func Inputln(problem string, required bool) string // 获取当前命令 func Current() (interface{}, bool) // 检查是否为sudo func IsSudo() bool // 检查是否为双击启动 func IsDoubleClickStartUp() bool // 锁定实例 func LockInstance() (clean func(), ok bool) // 检查错误 func CheckErr(err error, exit ...bool) // 显示帮助 func Help() // 显示错误 func Error(format string, v ...interface{}) ``` -------------------------------- ### Go: Get Current Time and Timestamps Source: https://github.com/sohaha/zlsgo/blob/master/docs/ztime.md This snippet demonstrates how to retrieve the current time in various formats, including string representations with custom formatting, time.Time objects, and Unix timestamps in seconds and microseconds. ```go // Get current time, supports custom format func Now(format ...string) string // Get current time object func Time() time.Time // Get current timestamp (seconds) func Clock() int64 // Get current timestamp (microseconds) func ClockMicro() int64 ``` -------------------------------- ### Go: zcli 信号处理函数 Source: https://github.com/sohaha/zlsgo/blob/master/docs/zcli.md 提供一个通道,用于接收单次终止信号。当系统发送终止信号时,该通道会发送一个布尔值 `true`。 ```go // 单次终止信号 func SingleKillSignal() <-chan bool ``` -------------------------------- ### Go: Timezone Management Functions Source: https://github.com/sohaha/zlsgo/blob/master/docs/ztime.md These functions manage timezone information, allowing you to get the current timezone location, set a specific timezone, retrieve the currently set timezone, and convert times to a specific timezone. ```go func Zone(zone ...int) *time.Location func SetTimeZone(zone int) *TimeEngine func GetTimeZone() *time.Location func In(tt time.Time) time.Time ``` -------------------------------- ### Go: Logger Instance Configuration Methods Source: https://github.com/sohaha/zlsgo/blob/master/docs/zlog.md Methods available on a `Logger` instance for configuring its behavior. This includes setting log levels, prefixes, flags, file output, formatters, and ignoring specific log types. Allows for fine-tuned control over individual loggers. ```go func (log *Logger) SetLogLevel(level int) func (log *Logger) GetLogLevel() int func (log *Logger) SetPrefix(prefix string) func (log *Logger) GetPrefix() string func (log *Logger) ResetFlags(flag int) func (log *Logger) SetFlags(flag int) func (log *Logger) GetFlags() int func (log *Logger) AddFlag(flag int) func (log *Logger) SetFile(filepath string, archive ...bool) func (log *Logger) SetSaveFile(filepath string, archive ...bool) func (log *Logger) SetFormatter(formatter Formatter) func (log *Logger) SetIgnoreLog(logs ...string) func (log *Logger) Write(b []byte) (n int, err error) func (log *Logger) Writer() io.Writer func (log *Logger) WriteBefore(fn ...func(level int, log string) bool) func (log *Logger) DisableConsoleColor() func (log *Logger) ForceConsoleColor() func (log *Logger) ColorTextWrap(color Color, text string) string func (log *Logger) ColorBackgroundWrap(color Color, backgroundColor Color, text string) string func (log *Logger) OpTextWrap(op Op, text string) string ``` -------------------------------- ### Dependency Injection with Worker Pool Source: https://github.com/sohaha/zlsgo/blob/master/docs/zpool.md This Go code illustrates dependency injection using a worker pool provided by the zpool library. It shows how to map dependencies (like a database connection string and a timestamp) and then use them within tasks executed by the pool. This simplifies managing shared resources and task context. ```Go // 依赖注入示例 // 工作池支持依赖注入 injectorPool := zpool.New(5) // 注册依赖 injectorPool.Injector().Map("数据库连接") injectorPool.Injector().Map(time.Now()) // 使用依赖注入的任务 for i := 0; i < 3; i++ { injectorPool.Do(func(dbConn string, startTime time.Time) { fmt.Printf("任务 %d 使用依赖: %s, 开始时间: %v\n", i, dbConn, startTime) }) } // 等待任务完成 injectorPool.Wait() // 关闭注入器工作池 injectorPool.Close() ``` -------------------------------- ### JSON Memory Pool Management in Go Source: https://github.com/sohaha/zlsgo/blob/master/docs/zjson.md Details the memory pool management functionalities for optimizing JSON processing. It includes functions to set, get, create, and reset the memory pool, as well as retrieve statistics about the pool's usage. ```go // 设置内存池 func SetPool(p Pool) // 获取内存池 func GetPool() Pool // 创建新的内存池 func NewPool() Pool // 重置内存池 func ResetPool() // 获取内存池统计信息 func GetPoolStats() PoolStats ``` -------------------------------- ### String Templating in Go Source: https://github.com/sohaha/zlsgo/blob/master/docs/zstring.md Enables the creation and processing of string templates with custom start and end tags. It allows resetting the template string and processing the template by writing to an `io.Writer` via a callback function. Useful for dynamic content generation. ```go // 使用自定义开始/结束标签创建模板 func NewTemplate(template string, startTag string, endTag string) (*Template, error) // 将模板渲染到 io.Writer,回调返回写入字节数与错误 func (t *Template) Process(w io.Writer, fn func(io.Writer, string) (int, error)) (int64, error) // 重设模板字符串并重新解析 func (t *Template) ResetTemplate(template string) error ``` -------------------------------- ### Utility Functions in Go for ZLSGO Source: https://github.com/sohaha/zlsgo/blob/master/docs/zhttp.md This section covers various utility functions for common tasks such as disabling chunked transfers, converting cookie strings, generating user agents, creating request bodies (JSON, XML, file), and establishing connections like JSON-RPC and SSE. ```go // 禁用分块传输 func DisableChunke(enable ...bool) // 转换 Cookie 字符串为映射 func ConvertCookie(cookiesRaw string) map[string]*http.Cookie // 生成随机用户代理 func RandomUserAgent() Header // 创建 JSON 请求体 func BodyJSON(v interface{}) *bodyJson // 创建 XML 请求体 func BodyXML(v interface{}) *bodyXml // 创建文件请求体 func File(path string, field ...string) interface{} // 创建新的 JSON-RPC 客户端 func NewJSONRPC(address string, path string, opts ...func(o *JSONRPCOptions)) (*JSONRPC, error) // 创建 SSE 连接 func SSE(url string, v ...interface{}) (*SSEEngine, error) ``` -------------------------------- ### Go 正则表达式处理字符串示例 Source: https://github.com/sohaha/zlsgo/blob/master/docs/zstring.md 展示了如何使用 zstring 库中的正则表达式功能来匹配、提取和替换字符串内容。支持单次匹配、多次匹配提取以及替换操作。适用于需要进行文本模式识别和处理的场景。 ```go package main import ( "fmt" "github.com/sohaha/zlsgo/zstring" ) func main() { // 正则表达式示例 text := "手机号码: 13812345678, 邮箱: test@example.com" // 提取手机号 phonePattern := `1[3-9]\d{9}` if zstring.RegexMatch(phonePattern, text) { phone, _ := zstring.RegexExtract(phonePattern, text) fmt.Printf("提取手机号: %v\n", phone) } // 提取邮箱 emailPattern := `\w+@\w+\.\w+` emails, _ := zstring.RegexExtractAll(emailPattern, text, -1) fmt.Printf("提取邮箱: %v\n", emails) // 替换敏感词 sensitiveText := "这是一个测试内容,包含敏感词" replaced, _ := zstring.RegexReplace("敏感词", sensitiveText, "***") fmt.Printf("替换后: %s\n", replaced) } ``` -------------------------------- ### Go: zcli 参数绑定函数 Source: https://github.com/sohaha/zlsgo/blob/master/docs/zcli.md 用于定义和绑定命令行参数到变量。支持多种数据类型(字符串、整数、浮点数、布尔值、时间间隔)和自定义类型/函数。 ```go // 设置变量 func SetVar(name, usage string) *v // 设置必需参数 func (v *v) Required() *v // 字符串类型 func (v *v) String(def ...string) *string // 整数类型 func (v *v) Int(def ...int) *int // 64位整数类型 func (v *v) Int64(def ...int64) *int64 // 无符号整数类型 func (v *v) Uint(def ...uint) *uint // 64位无符号整数类型 func (v *v) Uint64(def ...uint64) *uint64 // 64位浮点数类型 func (v *v) Float64(def ...float64) *float64 // 布尔类型 func (v *v) Bool(def ...bool) *bool // 时间间隔类型 func (v *v) Duration(def ...time.Duration) *time.Duration // 自定义类型 func (v *v) Var(value flag.Value, name string) *flag.Flag // 自定义函数 func (v *v) Func(fn func(s string) error) *flag.Flag ``` -------------------------------- ### Get Request Body - Various Collection Formats (Go) Source: https://github.com/sohaha/zlsgo/blob/master/docs/znet.md These functions retrieve the request body, parsing it from different collection formats like Postman, Swagger, and GraphQL. They take an interface{} as input and return an error if parsing fails. Dependencies include the respective libraries for each format. ```Go func (c *Context) BodyAria2cCollection(v interface{}) error func (c *Context) BodyWgetCollection(v interface{}) error func (c *Context) BodyCurlCollection(v interface{}) error func (c *Context) BodyHTTPieCollection(v interface{}) error func (c *Context) BodyRESTClientCollection(v interface{}) error func (c *Context) BodyThunderClientCollection(v interface{}) error func (c *Context) BodyBrunoCollection(v interface{}) error func (c *Context) BodyInsomniaCollection(v interface{}) error func (c *Context) BodyPostmanCollection(v interface{}) error func (c *Context) BodyAPIBlueprint(v interface{}) error func (c *Context) BodyRAML(v interface{}) error func (c *Context) BodySwagger(v interface{}) error func (c *Context) BodyOpenAPI(v interface{}) error func (c *Context) BodyGraphQL(v interface{}) error func (c *Context) BodySOAP(v interface{}) error func (c *Context) BodyXMLRPC(v interface{}) error func (c *Context) BodySExpressions(v interface{}) error func (c *Context) BodyEDN(v interface{}) error func (c *Context) BodyHocon(v interface{}) error func (c *Context) BodyIon(v interface{}) error func (c *Context) BodySmile(v interface{}) error func (c *Context) BodyUBJSON(v interface{}) error func (c *Context) BodyCBOR(v interface{}) error func (c *Context) BodyBson(v interface{}) error func (c *Context) BodyCapnProto(v interface{}) error func (c *Context) BodyFlatBuffers(v interface{}) error func (c *Context) BodyThrift(v interface{}) error func (c *Context) BodyAvro(v interface{}) error func (c *Context) BodyProtobuf(v interface{}) error func (c *Context) BodyMessagePack(v interface{}) error func (c *Context) BodyJSONLines(v interface{}) error func (c *Context) BodyTSV(v interface{}) error func (c *Context) BodyCSV(v interface{}) error func (c *Context) BodyProperties(v interface{}) error func (c *Context) BodyINI(v interface{}) error func (c *Context) BodyTOML(v interface{}) error func (c *Context) BodyYAML(v interface{}) error func (c *Context) BodyXML(v interface{}) error func (c *Context) BodyJSON(v interface{}) error ``` -------------------------------- ### Go 动态数组操作与集合工具 Source: https://context7.com/sohaha/zlsgo/llms.txt 演示了如何使用 zarray 库创建和操作动态数组,包括添加元素(unshift, push, add)、获取长度、按索引获取值、映射、过滤、查找、去重、差集、交集、分块等。还展示了 zarray 的随机选择、映射、过滤、查找、去重、差集、交集、分块等通用工具函数。 ```go package main import ( "fmt" "github.com/sohaha/zlsgo/zarray" ) func main() { // 动态数组 arr := zarray.NewArray(5) arr.Unshift("赵六") arr.Push("张三", "李四", "王五") arr.Add(2, "钱七") fmt.Printf("数组长度: %d\n", arr.Length()) if v, err := arr.Get(1); err == nil { fmt.Printf("索引1的值: %v\n", v) } // 映射操作 mapped := arr.Map(func(i int, v interface{}) interface{} { return fmt.Sprintf("[%d]%v", i, v) }) fmt.Printf("映射后: %v\n", mapped.Raw()) // 切片工具 numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} randomNum := zarray.Rand(numbers) fmt.Printf("随机数: %d\n", randomNum) randomNums := zarray.RandPickN(numbers, 3) fmt.Printf("随机选择3个: %v\n", randomNums) // 映射操作 doubled := zarray.Map(numbers, func(index int, item int) int { return item * 2 }) fmt.Printf("翻倍后: %v\n", doubled) // 并行映射 squared := zarray.Map(numbers, func(index int, item int) int { return item * item }, 4) fmt.Printf("平方后: %v\n", squared) // 过滤操作 evens := zarray.Filter(numbers, func(index int, item int) bool { return item%2 == 0 }) fmt.Printf("偶数: %v\n", evens) // 查找操作 if found, ok := zarray.Find(numbers, func(index int, item int) bool { return item > 5 }); ok { fmt.Printf("第一个大于5的数: %d\n", found) } // 去重操作 duplicates := []int{1, 2, 2, 3, 3, 3, 4, 4, 4, 4} unique := zarray.Unique(duplicates) fmt.Printf("去重后: %v\n", unique) // 差集操作 list1 := []int{1, 2, 3, 4, 5} list2 := []int{4, 5, 6, 7, 8} onlyIn1, onlyIn2 := zarray.Diff(list1, list2) fmt.Printf("只在list1中: %v\n", onlyIn1) fmt.Printf("只在list2中: %v\n", onlyIn2) // 交集操作 intersection := zarray.Intersection(list1, list2) fmt.Printf("交集: %v\n", intersection) // 分块操作 chunks := zarray.Chunk(numbers, 3) fmt.Printf("分块结果: %v\n", chunks) // 用户管理示例 type User struct { Name string Age int } users := []User{ {Name: "张三", Age: 25}, {Name: "李四", Age: 30}, {Name: "王五", Age: 35}, {Name: "赵六", Age: 28}, } youngUsers := zarray.Filter(users, func(index int, user User) bool { return user.Age < 30 }) fmt.Printf("年轻用户: %v\n", youngUsers) names := zarray.Map(users, func(index int, user User) string { return user.Name }) fmt.Printf("用户名列表: %v\n", names) } ``` -------------------------------- ### Go: TimeEngine for Centralized Time Operations Source: https://github.com/sohaha/zlsgo/blob/master/docs/ztime.md The TimeEngine provides a structured way to manage time operations with a consistent timezone. It offers methods for getting current time, formatting, parsing, and other time-related utilities, all bound to the engine's configured timezone. ```go func New(zone ...int) *TimeEngine func (e *TimeEngine) SetTimeZone(zone int) *TimeEngine func (e *TimeEngine) GetTimeZone() *time.Location func (e *TimeEngine) In(t time.Time) time.Time func (e *TimeEngine) Now(format ...string) string func (e *TimeEngine) Time(realTime ...bool) time.Time func (e *TimeEngine) Clock() int64 func (e *TimeEngine) FormatTime(t time.Time, format ...string) string func (e *TimeEngine) FormatTimestamp(timestamp int64, format ...string) string func (e *TimeEngine) Unix(tt int64) time.Time func (e *TimeEngine) UnixMicro(tt int64) time.Time func (e *TimeEngine) Parse(str string, format ...string) (time.Time, error) func (e *TimeEngine) Week(t time.Time) int func (e *TimeEngine) MonthRange(year, month int) (beginTime, endTime int64, err error) ``` -------------------------------- ### Go: Parse and Query JSON Data with zjson Source: https://github.com/sohaha/zlsgo/blob/master/docs/zjson.md This snippet demonstrates how to parse JSON strings and byte arrays, unmarshal JSON into Go structs, and query JSON data using path syntax. It includes functions for getting values, checking key/path existence, and retrieving multiple values. ```go import "github.com/sohaha/zlsgo/zjson" // Parse JSON string func Parse(data string) *Res // Parse JSON byte array func ParseBytes(data []byte) *Res // Unmarshal JSON to struct func Unmarshal(data []byte, v interface{}) error // Get byte array value by key func (j *Res) GetBytes(key string) []byte // Get multiple values by keys func (j *Res) GetMultiple(keys ...string) []interface{} // Get multiple byte array values by keys func (j *Res) GetMultipleBytes(keys ...string) [][]byte // Check if a key exists func (j *Res) Exists(key string) bool // Get value by path func (j *Res) Get(path string) *Res // Get value by path as byte array func (j *Res) GetBytes(path string) []byte // Get multiple values by path func GetMultiple(json, path string, keys ...string) []interface{} // Get multiple values by path as byte array func GetMultipleBytes(json []byte, path string, keys ...string) [][]byte // Check if a path exists func Exists(json, path string) bool // Check if a path exists in byte array JSON func ExistsBytes(json []byte, path string) bool ``` -------------------------------- ### Node Health Check and Recovery Example Source: https://github.com/sohaha/zlsgo/blob/master/docs/zpool.md This Go code demonstrates how to periodically check the health of nodes managed by an advanced load balancer. It includes logic to detect unavailable nodes, attempt recovery, and mark them as available again. This pattern is crucial for maintaining high availability in distributed systems. ```Go // 节点健康检查示例 go func() { ticker := time.NewTicker(10 * time.Second) defer ticker.Stop() for range ticker.C { advancedBalancer.WalkNodes(func(node string, available bool) bool { if !available { fmt.Printf("节点 %s 不可用,尝试恢复...\n", node) // 模拟健康检查 if time.Now().Unix()%60 == 0 { // 每分钟恢复一个节点 advancedBalancer.Mark(node, true) fmt.Printf("节点 %s 已恢复\n", node) } } return true }) } }() ``` -------------------------------- ### Go: Executing Commands with Specific I/O and Callbacks Source: https://github.com/sohaha/zlsgo/blob/master/docs/zshell.md Offers advanced command execution capabilities, allowing redirection of standard input, output, and error streams. It also supports executing commands with pre- and post-execution callback functions for finer control over the command lifecycle. ```go func ExecCommand(ctx context.Context, command []string, stdIn io.Reader, stdOut io.Writer, stdErr io.Writer, opt ...func(o *Options)) (code int, outStr, errStr string, err error) func ExecCommandHandle(ctx context.Context, command []string, bef func(cmd *exec.Cmd) error, aft func(cmd *exec.Cmd, err error)) (code int, err error) ``` -------------------------------- ### Go 参数解析和编译示例 Source: https://github.com/sohaha/zlsgo/blob/master/docs/zutil.md 展示了如何使用 zutil.NewArgs() 创建参数管理器,并通过 Var() 方法添加不同类型的数据。随后,可以利用 CompileString() 和 Compile() 方法将这些参数格式化为字符串或 SQL 查询语句。这对于构建动态查询或格式化输出非常方便。 ```go package main import ( "fmt" "github.com/sohaha/zlsgo/zutil" ) func main() { args := zutil.NewArgs() // 添加参数 args.Var("张三") args.Var(25) args.Var(true) // 编译字符串 result := args.CompileString("姓名: {}, 年龄: {}, 激活: {}") fmt.Printf("编译结果: %s\n", result) // 编译查询 query, values := args.Compile("SELECT * FROM users WHERE name = ? AND age = ?") fmt.Printf("查询: %s, 参数: %v\n", query, values) } ``` -------------------------------- ### Go 泛型哈希映射与提供者模式 Source: https://context7.com/sohaha/zlsgo/llms.txt 展示了如何使用 zarray.NewHashMap 创建和操作泛型哈希映射,包括设置键值对、获取值、比较并交换(CAS)操作。还演示了提供者模式(ProvideGet)用于获取值或在值不存在时计算并设置。 ```go package main import ( "fmt" "github.com/sohaha/zlsgo/zarray" ) func main() { // 哈希映射 hashMap := zarray.NewHashMap[string, int]() hashMap.Set("Alice", 25) hashMap.Set("Bob", 30) hashMap.Set("Charlie", 35) if age, ok := hashMap.Get("Alice"); ok { fmt.Printf("Alice的年龄: %d\n", age) } // 提供者模式 actualAge, loaded, computed := hashMap.ProvideGet("Eve", func() (int, bool) { return 28, true }) fmt.Printf("Eve的年龄: %d, 已存在: %t, 计算得出: %t\n", actualAge, loaded, computed) // 比较并交换 swapped := hashMap.CAS("Bob", 30, 31) fmt.Printf("CAS操作: %t\n", swapped) } ``` -------------------------------- ### Go MD5, Base64, AES, RSA 加密与解密示例 Source: https://github.com/sohaha/zlsgo/blob/master/docs/zstring.md 演示了 zstring 库提供的多种加密和编码功能,包括 MD5 哈希、Base64 编码与解码、AES 对称加密与解密(使用 16 字节密钥)、以及 RSA 非对称加密与解密(包括密钥生成)。适用于数据安全和传输场景。 ```go package main import ( "fmt" "github.com/sohaha/zlsgo/zstring" ) func main() { // MD5 哈希示例 originalText := "要加密的文本" md5Hash := zstring.Md5(originalText) fmt.Printf("MD5 哈希: %s\n", md5Hash) // Base64 编码示例 base64Encoded := zstring.Base64EncodeString(originalText) fmt.Printf("Base64 编码: %s\n", base64Encoded) // Base64 解码 base64Decoded, _ := zstring.Base64DecodeString(base64Encoded) fmt.Printf("Base64 解码: %s\n", base64Decoded) // AES 加密示例 key := "1234567890123456" // 16字节密钥 plaintext := "要加密的敏感数据" // AES 加密 encrypted, err := zstring.AesEncryptString(plaintext, key) if err != nil { fmt.Printf("AES 加密失败: %v\n", err) } else { fmt.Printf("AES 加密结果: %s\n", encrypted) // AES 解密 decrypted, err := zstring.AesDecryptString(encrypted, key) if err != nil { fmt.Printf("AES 解密失败: %v\n", err) } else { fmt.Printf("AES 解密结果: %s\n", decrypted) } } // RSA 加密示例 // 生成RSA密钥对 privateKey, publicKey, err := zstring.GenRSAKey(2048) if err != nil { fmt.Printf("生成RSA密钥失败: %v\n", err) } else { // RSA 加密 rsaEncrypted, err := zstring.RSAEncryptString(plaintext, string(publicKey)) if err != nil { fmt.Printf("RSA 加密失败: %v\n", err) } else { fmt.Printf("RSA 加密成功\n") // RSA 解密 rsaDecrypted, err := zstring.RSADecryptString(rsaEncrypted, string(privateKey)) if err != nil { fmt.Printf("RSA 解密失败: %v\n", err) } else { fmt.Printf("RSA 解密结果: %s\n", rsaDecrypted) } } } } ```