Go-Sail Documentation

website·Indexed 31 days ago

https://go-sail.dev

A lightweight framework for building reliable services in Go. It provides a comprehensive suite of tools including an HTTP toolkit for routing and middleware, GORM-based database interaction, JWT control plane for security, and integrated support for components like Kafka, Etcd, Nacos, and Prometheus monitoring.

Tokens
30.4K
Snippets
172
Records
193
Agent score
61%

What's inside Go-Sail

  1. Overview of the Go-Sail HTTP toolkit

    The Go-Sail HTTP toolkit is a set of utilities designed to standardize web communication. It provides three primary capabilities: unified response structures, routing middleware for common HTTP tasks, and standardized request and response entity specifications (DTOs and VOs).
  2. Overview of the go-sail common toolkit

    The go-sail common toolkit is a collection of utility methods designed for everyday development operations. It provides specialized tools for AES, Base64, CRC, Datetime, File, Heap, IP, MD5, Redis lock, RSA, Signal, SM4, String, Time, Validator, Version, and Webpush.
  3. Overview of Go-Sail system constants packages

    Go-Sail provides a set of predefined system constants organized into specific packages to maintain consistency across business logic and framework operations. The available constant packages include:

    • code: Defines business response codes and error codes. Custom codes and messages can be injected using RegisterCodeSingle() and RegisterCodeTable().
    • errors: Defines error codes and error messages, with built-in support for internationalization (i18n).
    • i18n: Defines language codes based on the ISO-3166-1 standard.
    • keys: Defines prefix and suffix identifiers for public and private keys.
    • sail: Contains framework-specific metadata, including the logo characters and version number.
    • status: Defines boolean values used to indicate successful or failed responses.
    • time: Defines timezone characters and date printing templates for global time zones.
  4. Overview of the Go-Sail JWT component

    The JWT component in Go-Sail provides a simplified wrapper for signing and verifying tokens. It is automatically activated during application startup based on the provided configuration.
  5. Overview of the Go-Sail Framework

    Go-Sail is a lightweight progressive web framework implemented in Go. It acts as a starting point in the Golang ecosystem, integrating existing components to help developers build stable and reliable services without focusing on trivial infrastructure matters. It is highly flexible and can be used to build entire service architectures, integrated into specific modules, or used for individual features.
  6. Overview of the Go-Sail database component

    The Go-Sail database component is a wrapper around gorm.io/gorm that handles database connection management and log processing. It supports MySQL, PostgreSQL, SQL Server, SQLite, and ClickHouse. The component is automatically initialized when Go-Sail starts (if enabled) and is accessed via the sail package.
  7. Implement log tracing across the call chain in Go-Sail

    Go-Sail provides a built-in router middleware called LogTrace that is automatically injected during startup. This middleware generates a unique requestId and injects a logger instance containing this identifier into the request context. This allows developers to trace a single request's entire lifecycle across handlers and service layers. In microservices environments, this requestId can be passed between services to maintain a distributed trace, similar to tools like Zipkin or Skywalking.
  8. Perform database transactions in Go-Sail

    When using transactions, all operations within the transaction must be performed on the same connection instance (the transaction object tx) to ensure consistency. Using separate instances (e.g., calling GetDBW() inside a transaction started by GetDBR()) will lead to incorrect behavior.
    import (
        "gorm.io/gorm"
        "github.com/keepchen/go-sail/v3/sail"
    )
    
    func main() {
        // Correct: Use the provided tx instance for all operations
        sail.GetDBW().Transaction(func(tx *gorm.DB) error {
            err := tx.Model(...).Where(...).First(...).Error
            if err != nil {
                return err
            }
            err = tx.Model(...).Where(...).Updates(...).Error
            return err
        })
    }
  9. Retrieve the default Etcd instance in Go-Sail

    The Etcd component in Go-Sail is a wrapper around the go.etcd.io/etcd library. If the Etcd component is enabled, Go-Sail automatically initializes it upon startup. Developers can access the initialized instance using the sail.GetEtcdInstance() method.
    import (
        "github.com/keepchen/go-sail/v3/sail"
    )
    
    func main() {
        sail.GetEtcdInstance()
    }
  10. Integrate Etcd for configuration management

    Go-Sail provides utilities to read and monitor configuration from Etcd. You must initialize the Etcd client before performing KV operations or setting up watches.
    import (
        "context"
        "github.com/keepchen/go-sail/v3/lib/etcd"
    )
    
    func main() {
        conf := etcd.Conf{ /* config options */ }
        etcd.Init(conf)
    
        // Get key-value
        etcd.GetInstance().KV.Get()
    
        // Watch key-value
        callback := func(k, v []byte()) { /* handle change */ }
        ctx := context.Background()
        etcd.Watch(ctx, "key", callback)
    }
  11. Initialize and use the Go-Sail logger

    The Go-Sail logger is an encapsulation of the uber-go/zap library. It is automatically initialized when Go-Sail starts (if enabled). Developers can access the logger instance globally using the sail.GetLogger() method.
    import (
        "github.com/keepchen/go-sail/v3/sail"
    )
    
    func main() {
        sail.GetLogger().Error("looks like something went wrong", 
            zap.String("err", err.Error()))
    }
  12. Bind and validate request parameters in handlers

    In the handler function, use c.ShouldBind() to map request data to the request entity and call the entity's Validator() method to ensure data integrity. Use sail.Response(c).Failure400() to return errors for invalid parameters.
    func UserInfo(c *gin.Context) {
        var form request.UserInfoReqVO
        
        // Bind parameters
        if err := c.ShouldBind(&form); err != nil {
            sail.Response(c).Failure400(sailConstants.ErrRequestParamsInvalid)
            return
        }
        
        // Validate parameters
        if code, err := form.Validator(); err != nil {
            loggerSvc.Warn("[UserInfo] form field validate failed", zap.Errors("errors", []error{err}))
            sail.Response(c).Failure400(code)
            return
        }
        // ... business logic
    }