go-gin-api Framework

repository·master·Indexed 27 days ago

https://github.com/xinliangnote/go-gin-api

A modular API framework built on Gin designed to accelerate business development. It provides enterprise features including rate limiting, observability (Prometheus, pprof), database integration via GORM, GraphQL support, and Dynamic Data Masking (DDM) for sensitive information. The framework includes a code generation tool (gormgen) for GORM models and a lightweight alternative version called gin-api-mono.

Tokens
4.8K
Snippets
6
Records
37
Agent score
91%

What's inside go-gin-api

  1. Overview of go-gin-api

    master

    go-gin-api is a modular API framework built on top of Gin. It is designed to accelerate business development by encapsulating common functionalities while enforcing project constraints to prevent disorganized coding practices.

    Note: This project is intended for reference and learning. Use caution when deploying it in production environments.

  2. Overview of go-gin-api features

    master

    go-gin-api is a modular API framework built on top of Gin. It is designed to accelerate business development by encapsulating common functions and enforcing structured coding patterns to prevent architectural chaos.

    Key Features:

    • API Management: Rate-limiting (via rate), CORS support (via cors), and standard RESTful API return values.
    • Documentation & Schema: Automatic RESTful API documentation via Swagger and GraphQL support via gqlgen.
    • Observability: Metrics monitoring and alerting with Prometheus, internal invocation tracing, and visualized performance analysis via pprof.
    • Reliability: Email notifications on panic and uniformly defined error codes using errno.
    • Data & Config: ORM support via gorm, Redis support via go-redis, and configuration management via viper.
    • Logging: Structured, leveled logging using zap.
    • Developer Tools: CURD and controller code generators, and a web interface supported by the Light Year Admin template.
  3. Integrated components in go-gin-api

    master

    The framework comes with a wide range of integrated components for enterprise-grade API development:

    • Rate Limiting: Supports golang.org/x/time/rate.
    • Error Handling: Supports unified error code definitions via errno and email notifications upon panic.
    • Security & CORS: Supports rs/cors for cross-origin resource sharing.
    • Observability:
      • Metrics: Prometheus.
      • Tracing: Internal distributed tracing support.
      • Profiling: pprof.
    • Documentation: Swagger for API documentation generation.
    • Query Languages: GraphQL support.
    • Logging: zap for high-performance logging.
    • Configuration: viper for configuration file parsing.
    • Data & Storage:
    • Communication:
      • RESTful API: Standardized return value specifications.
      • WebSocket: Real-time communication via gorilla/websocket.
    • Automation & Tools:
      • Code Generation: Generates CURD (Create, Read, Update, Delete) code and controller methods.
      • Scheduled Tasks: cron with a web interface for configuration.
    • Admin Interface: A web UI based on the Light Year Admin template.
  4. Generate GORM models using gormgen.sh

    master

    You can generate GORM models from an existing database by executing the gormgen.sh script located in the ./scripts/ directory. The script requires database connection details and target table names.

    Arguments:

    • addr: Database address (e.g., 127.0.0.1:3306)
    • user: Database username (e.g., root)
    • pass: Database password (e.g., root)
    • name: Database name (e.g., go_gin_api)
    • tables: Table names. Use * for all tables, or provide a comma-separated list for specific tables (e.g., user_demo,order_demo).
    ./scripts/gormgen.sh 127.0.0.1:3306 root root go_gin_api user_demo
  5. Install and use Bootstrap Table Pipelining

    master

    The Bootstrap Table Pipelining plugin enables client-side data caching for server-side requests. This optimizes performance for large datasets by reducing the number of server requests during page changes. Instead of requesting a single page, the plugin requests a 'cache window' of data (defined by pipelineSize) and caches it locally.

    Important Server-Side Requirement: Your server-side implementation MUST use the limit (equal to pipelineSize) and offset parameters to return only the data within the requested cache window, along with the total number of rows.

    <!-- Assumes bootstrap and bootstrap-table assets are already imported -->
    <script src="/path/to/bootstrap-table-pipeline.js"></script>
    
    <table id="pipeline_table" 
        class="table table-striped"
        data-method='post'
        data-use-pipeline="true"
        data-pipeline-size="5000"
        data-pagination="true"
        data-side-pagination="server"
        data-page-size="50">
        <thead
            <tr
            <th data-field="type" data-sortable="true">Type</th>
            <th data-field="value" data-sortable="true">Value</th>
            <th data-field="date" data-sortable="true">Date</th>
        </tr>
    </thead>
    </table>
  6. Use Dynamic Data Masking (DDM) for sensitive data

    master

    Dynamic Data Masking (DDM) is used to prevent sensitive data from being exposed to unauthorized users by masking specific parts of the data. The ddm package provides specialized types for common sensitive data formats. Supported masking types include:

    TypeRequirementExampleDescription
    Phone NumberFirst 3, last 4 visible132****7986Fixed 11-digit number
    Email AddressFirst 1, last 1 visiblel**w@gmail.comMasks only the part before the @
    NameHide surname*鸿章Hides the surname
    PasswordNo output******
    Bank Card NumberFirst 6, last 4 visible622888******5676Up to 19 digits
    ID Card NumberFirst 1, last 1 visible1******7Fixed 18-digit number
  7. Use gin-api-mono for lightweight requirements

    master

    If you require a simpler, more lightweight API framework, use gin-api-mono.

    Compared to the full go-gin-api, gin-api-mono:

    • Removes certain integrated features and UI components to remain concise.
    • Features upgraded framework code for improved performance and stability.
    • Allows developers to select only the necessary functionalities with less overhead.
  8. Configure Bootstrap Table Pipelining options

    master

    Use the following options to control the pipelining behavior in your Bootstrap Table:

    • usePipeline (Boolean): Set to true to enable the pipelining feature. Default is false.
    • pipelineSize (Integer): The size of each cache window. Must be greater than 0. Default is 1000.

    Note on pipelineSize calculation: The plugin automatically rounds the pipelineSize up to the nearest value that is evenly divisible by the current page-size to ensure consistent windowing.

  9. Understand the generated GORM Query Builder pattern

    master

    The gormgen tool generates a specialized Query Builder for each model to provide a type-safe, fluent API for database operations. The generated code includes a model struct and a corresponding Query Builder struct.

    Key features of the generated Query Builder include:

    • Fluent Interface: Methods like Limit, Offset, and Where... return the builder instance to allow chaining.
    • CRUD Operations: Built-in methods for Create, Updates, Delete, Count, First, QueryOne, and QueryAll.
    • Type-Safe Filtering: For every field in the model, the generator creates specific Where[FieldName], Where[FieldName]In, and Where[FieldName]NotIn methods.
    • Ordering: OrderBy[FieldName](asc bool) methods for sorting results.

    Note: Files generated by this tool are marked with a warning header and should not be edited manually, as changes will be overwritten during regeneration.

  10. Use the mysqlmd CLI tool to generate documentation and models

    master

    The mysqlmd tool connects to a MySQL database and automatically generates two types of files for each table: a Markdown documentation file (gen_table.md) containing a detailed schema table, and a Go model file (gen_model.go) containing a GORM-compatible struct.

    Files are organized into a directory structure under ./internal/repository/mysql/[table_name]/.

  11. Use the mfmt tool to sort Go imports

    master

    The mfmt tool is a CLI utility that automatically sorts and groups Go import statements within a project. It organizes imports into three distinct groups:

    1. Standard Library: Packages from the Go standard library.
    2. Module Group: Packages that belong to the current project's module (identified via go.mod).
    3. Others: All other third-party dependencies.

    When running, the tool scans the current directory and its subdirectories, ignores vendor directories, hidden files, and .pb.go files, and applies formatting. If a file's content changes due to the sorting/formatting, the tool prints the file path to standard output.