zlsgo Toolkit

repository·master·Indexed 21 days ago

https://github.com/sohaha/zlsgo

A modular, high-performance, and type-safe Go toolkit providing specialized libraries for web development (znet), HTTP client operations (zhttp), logging (zlog), and various data processing tasks. It includes comprehensive modules for array and slice manipulation (zarray), caching (zcache), CLI tools (zcli), dependency injection (zdi), and other utility packages for JSON, file operations, and synchronization.

Tokens
49.1K
Snippets
161
Records
220
Agent score
77%

What's inside zlsgo

  1. Overview of the znet module

    master
    The znet module is a high-performance toolkit for building Web applications in Go. It provides a comprehensive suite of networking and web-related capabilities, including an HTTP server engine, flexible routing with middleware support, template engines, Server-Sent Events (SSE), and JSON-RPC support. It also includes utility tools for IP address handling and network configuration.
  2. Overview of zlsgo modules

    master

    The zlsgo project is organized into several functional modules:

    Core Modules

    • zarray: Array operations
    • zcache: Caching
    • zcli: CLI tools
    • zdi: Dependency injection
    • zerror: Error handling

    File and Data Modules

    • zfile: File operations
    • zhttp: HTTP client
    • zjson: JSON processing
    • ztype: Type handling

    Network and Web Modules

    • znet: Web framework
    • zpool: Resource pool management
    • zpprof: Performance profiling

    Utility Modules

    • zlog: Logging
    • zreflect: Reflection tools
    • zshell: Shell command execution
    • zstring: String processing
    • zsync: Synchronization primitives
    • ztime: Time handling
    • zutil: General utilities
    • zvalid: Data validation
    • zlocale: Internationalization (i18n)
  3. Overview of the zutil module

    master

    The zutil module is a collection of general-purpose utility and helper functions for Go development. It provides high-level abstractions for common tasks including:

    • Reflection Tools: Utilities for inspecting and manipulating types and values.
    • Atomic Operations: Thread-safe wrappers for various primitive types.
    • Retry Mechanism: Function retry logic with configurable delays.
    • Channel Management: Simplified creation of buffered, unbuffered, and unbounded channels.
    • Buffer Pool: Management of bytes.Buffer for object reuse.
    • Memory Monitoring: Tools to monitor and limit heap memory usage.
    • Environment & System: Helpers for environment variables, OS detection, and system info.
    • Argument Parsing: Utilities for command-line argument handling.
    • Concurrency Patterns: Implementations of Once and Option patterns.
  4. Overview of the ztype module

    master

    The ztype module provides a flexible type conversion toolkit and a dynamic type system for Go. It is designed to allow developers to safely access values and perform automatic type conversions with high performance and efficient memory management.

    Key capabilities include:

    • Type Wrapping: Safe wrapping and access of various types.
    • Type Conversion: Automatic type conversion and validation.
    • Path Access: Accessing nested values using path expressions.
    • Slice & Map Handling: Safe operations on slices and maps.
    • Struct Building: Dynamic construction of structs.
    • Performance: Optimized for high execution efficiency and concurrency support.
  5. Use zreflect for enhanced reflection operations

    master
    The zreflect module provides a convenient wrapper around Go's standard reflect package. It simplifies common tasks such as method invocation, field access (including unexported fields), type checking, and struct traversal. It introduces high-level wrappers for reflect.Type and reflect.Value to make the API more ergonomic.
  6. Explore zlsgo modules

    master

    zlsgo is a modular library. You can import only the specific modules you need to keep your binary lightweight.

    Core Modules

    • zarray: Array operations
    • zcache: Cache library
    • zcli: Command-line interface
    • zdi: Dependency injection
    • zerror: Error handling

    File and Data Modules

    • zfile: File operations
    • zhttp: HTTP client
    • zjson: JSON processing
    • ztype: Type handling

    Network and Web Modules

    • znet: Web framework
    • zpool: Resource pool management
    • zpprof: Performance profiling

    Utility Modules

    • zlog: Logger
    • zreflect: Reflection utilities
    • zshell: Shell command execution
    • zstring: String processing
    • zsync: Synchronization primitives
    • ztime: Time handling
    • zutil: Common utilities
    • zvalid: Data validation
    • zlocale: Internationalization
  7. How to implement best practices with zarray

    master

    When using the zarray module, follow these best practices:

    1. Use Type-Safe Operations: Leverage Go generics (e.g., NewHashMap[string, int]) to ensure type safety and avoid interface casting.
    2. Choose the Right Data Structure: Use NewArray for dynamic resizing needs, NewSortMap when order matters, and NewHashMap for high-performance key-value lookups.
    3. Implement Proper Error Handling: Always check the error return values from methods like Get or IndexMap.
    4. Monitor Performance: Be mindful of the concurrency parameter in Map functions; while it can speed up processing, excessive goroutines can lead to overhead.
  8. Core capabilities of znet

    master

    The znet module is organized into several functional areas:

    • HTTP Server: A high-performance engine for serving HTTP requests.
    • Routing & Middleware: A flexible system for configuring routes and applying middleware logic.
    • Template Engine: Support for standard Go templates and custom template implementations.
    • Real-time Communication: Built-in support for Server-Sent Events (SSE).
    • RPC: Support for JSON-RPC services.
    • Networking Utilities: Tools for IP address processing, validation, port management, and network configuration.
  9. Choose the right Load Balancer strategy

    master

    Select a BalancerStrategy based on your specific use case:

    StrategyDescriptionBest Use Case
    StrategyRandomRandomly selects an available node.General load dispersion.
    StrategyLeastConnSelects the node with the fewest active connections.High availability and preventing node saturation.
    StrategyRoundRobinCycles through nodes in order.Simple, predictable scenarios.
    StrategyWeightedSelects nodes based on their assigned weight.Performance-sensitive environments with heterogeneous hardware.
  10. Skip sub-fields during recursive traversal

    master

    When using ForEach or ForEachValue for recursive traversal, you can prevent the function from descending into specific fields by returning the zreflect.SkipChild error in your callback function.

    err := zreflect.ForEachValue(reflect.ValueOf(data), func(parent []string, index int, tag string, field reflect.StructField, val reflect.Value) error {
        if field.Name == "SkipField" {
            return zreflect.SkipChild
        }
        // Process field...
        return nil
    })
  11. Implement PreInvoker for optimized function calls

    master

    If you need to optimize the way functions are invoked (e.g., to avoid reflection overhead or implement custom logic), implement the PreInvoker interface. An object implementing PreInvoker will be detected by IsPreInvoker and used by the injector's Invoke method to handle the call manually.

    type OptimizedHandler struct{}
    
    func (h *OptimizedHandler) Invoke(args []interface{}) ([]reflect.Value, error) {
        // Custom optimized logic here
        return []reflect.Value{reflect.ValueOf(result)}, nil
    }
    
    // The injector will use this if it implements PreInvoker
    results, err := injector.Invoke(&OptimizedHandler{}, "arg1")
  12. Use ProvideGet for lazy loading in zcache

    master

    The ProvideGet pattern allows you to attempt to retrieve a value from the cache, and if it doesn't exist, execute a callback function to fetch/generate the data and automatically store it in the cache with the specified expiration. This is useful for reducing database load (the 'cache aside' pattern).

    // If "user:123" is missing, the callback runs, and the result is cached for 30 minutes
    userData, exists := zcache.ProvideGet("user:123", func() (interface{}, bool) {
        // Simulate database fetch
        user := map[string]interface{}{"id": 123, "name": "ZhangSan"}
        return user, true
    }, time.Minute*30)