# basic-go **Repository Path**: usmos/basic-go ## Basic Information - **Project Name**: basic-go - **Description**: 基础go, 通用的go代码基础功能封装, 作用于基于此封装快速的进行代码模块的开发,减少每一个子项目重复的代码编写 - **Primary Language**: Go - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-10-08 - **Last Updated**: 2026-10-10 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # basic-go A collection of common Go infrastructure libraries. It consolidates the boilerplate that every sub-project repeats — configuration, logging, database, caching, lifecycle management, and more — into a set of ready-to-use, independently importable modules, so business projects can focus on the business itself. ## Modules | Package | Purpose | Docs | |---|---|---| | [app](app) | application bootstrap: config loading → logging → component wiring (Wire) → resource init hooks → route registration → HTTP startup with graceful shutdown, collapsing main boilerplate | [README](app/README.md) | | [config](config) | viper-based configuration: defaults / env vars / config files / directory scanning, hot reload and save-back | [README](config/README.md) | | [logger](logger) | zap + lumberjack logging: multiple output cores, rolling archives, dedicated file for error-and-above, global handle replacement | [README](logger/README.md) | | [database](database) | gorm-based database access: unified interface, global connection, closure-style transaction helper, pagination scope, driver sub-packages on demand (mysql / postgres / sqlite) | [README](database/README.md) | | [cache](cache) | go-redis-based caching: basic commands (zero context params), distributed locks, delay queue | [README](cache/README.md) | | [errcode](errcode) | unified business error codes: convention "ten-thousands digit + HTTP status" (e.g. 10404) maps automatically to 4xx/5xx, compatible with errors.Is/As, renders the uniform {code,msg,data} envelope with ginx | [README](errcode/README.md) | | [snowflake](snowflake) | snowflake ID generator: 64-bit trend-increasing IDs, clock-rollback protection, workerID via env var or egress-IP derivation, zero external dependencies | [README](snowflake/README.md) | | [cron](cron) | thin wrapper over robfig/cron/v3: configurable timezone / seconds / skip-if-busy, spec validated at registration, panic auto-recover, per-run duration logged | [README](cron/README.md) | | [trace](trace) | OpenTelemetry-based distributed tracing: configurable OTLP export (gRPC/HTTP), HTTP server spans, W3C cross-service propagation, trace id bridged into the X-Request-Id logging convention | [README](trace/README.md) | | [lifecycle](lifecycle) | context-based application lifecycle: graceful start/stop, signal handling | [README](lifecycle/README.md) | | [ginx](ginx) | gin-based web service: config-driven startup, graceful shutdown, centralized route registration; built-in middlewares (CORS / rate limiting / TraceID / binding validation), unified response rendering & pagination, telemetry endpoints (metrics / pprof), dual probes & drain-on-shutdown | [README](ginx/README.md) | ## Requirements - Go 1.26+ ## Installation ```bash go get gitee.com/usmos/basic-go ``` Packages are split by module — business projects import only what they use, and unused modules never enter the dependency graph (e.g. importing only `database` will not pull in the `cache` module's go-redis dependency). ## Quick Start The real-world pattern, as demonstrated in [example/tata](example/tata) — a business `main` does three things: declare the config struct, register routes, and call `app.MustRun`: ```go package main import ( "errors" "strconv" "gitee.com/usmos/basic-go/app" "gitee.com/usmos/basic-go/cache" "gitee.com/usmos/basic-go/cron" "gitee.com/usmos/basic-go/database" "gitee.com/usmos/basic-go/database/mysql" "gitee.com/usmos/basic-go/errcode" "gitee.com/usmos/basic-go/ginx" "gitee.com/usmos/basic-go/ginx/middleware" "gitee.com/usmos/basic-go/logger" "gitee.com/usmos/basic-go/snowflake" "gitee.com/usmos/basic-go/trace" "github.com/gin-gonic/gin" "gorm.io/gorm" ) // Conf is the config struct: embed app.Base for the server / log sections, // and declare business sections yourself type Conf struct { app.Base Database mysql.MySQL `yaml:"database"` Redis cache.Redis `yaml:"redis"` Cron cron.Config `yaml:"cron"` Trace trace.Config `yaml:"trace"` } // User is a sample table model; binding tags drive param validation type User struct { ID int64 `gorm:"primaryKey" json:"id"` Name string `gorm:"size:64" binding:"required" json:"name"` Email string `gorm:"size:128" binding:"omitempty,email" json:"email"` } // Long-lived business component shared between Init/Close hooks var orderQueue *cache.DelayQueue func main() { // Route registration: ginx centralized registry, built and validated at startup api := ginx.NewGroup("/api/v1") api.POST("/users", middleware.Bind(createUser)) // validation failure -> 400 {code:10400} api.GET("/users/:id", getUser) // errcode maps to 404 {code:10404} api.GET("/users", listUsers) // pagination: BindPage + RenderPage // One call: config loading -> logging -> component wiring (Wire) -> business // init -> HTTP startup -> release after graceful shutdown app.MustRun(&app.Boot[Conf]{ EnvPrefix: "TATA_GO", // env var prefix; empty disables env overrides Watch: true, // hot reload; file changes back-fill and trigger OnChange Wire: func(c *Conf) []app.Component { // one component per line: Init in order, Close in reverse, auto-rollback on failure return []app.Component{ trace.NewBoot(c.Trace), // first: closed last on reverse release, in-flight spans fully flushed snowflake.NewBoot(), // workerID auto-derived (env var -> egress IP) database.NewBoot(&c.Database, &User{}), // connect + auto-migrate cache.NewBoot(&c.Redis), // connect (with ping probe) cron.NewBoot(c.Cron, cron.Job{ // build scheduler + register jobs + start Spec: "*/5 * * * *", Name: "clean-expired", Run: func() { logger.Info("cron fired: cleaning expired data") }, }), } }, Init: func(c *Conf) error { // business-specific init; an error aborts startup // Readiness: /readyz returns 200 only once injected; it flips to 503 // during drain to steer the LB away ginx.SetReadyChecker(func() bool { return cache.Client() != nil }) // Delay queue: the consumer goroutine stops via the Close hook orderQueue = cache.NewDelayQueue("orders:delay", func(payload string) error { logger.Info("delayed order processing: " + payload) return nil }) return orderQueue.Start() }, Close: func() { orderQueue.Stop() }, // release business components after HTTP stops; Wire components follow in reverse OnChange: func(c *Conf) { // hot-reload callback (requires Watch), optional logger.Info("config hot reload done, new values applied") }, }) } // createUser: generic binding + snowflake ID + closure transaction + unified rendering func createUser(c *gin.Context, req *User) { id, err := snowflake.Next() if err != nil { ginx.RenderError(c, err) return } req.ID = id err = database.Tx(func(tx *gorm.DB) error { return tx.Create(req).Error // any error rolls back }) ginx.Render(c, err, req) } // getUser: underlying errors become semantic codes; the response maps to 404 func getUser(c *gin.Context) { id, err := strconv.ParseInt(c.Param("id"), 10, 64) if err != nil { ginx.RenderError(c, errcode.ErrInvalidParams.WithMsg("user id must be numeric")) return } var user User err = database.DB().First(&user, id).Error if errors.Is(err, gorm.ErrRecordNotFound) { ginx.RenderError(c, errcode.ErrNotFound.WithMsg("user not found").WithErr(err)) return } ginx.Render(c, err, &user) } // listUsers: pagination via ginx.BindPage + database.Paginate + ginx.RenderPage func listUsers(c *gin.Context) { page := ginx.BindPage(c) var ( total int64 users []User ) db := database.DB().Model(&User{}) if err := db.Count(&total).Error; err != nil { ginx.RenderError(c, err) return } err := db.Scopes(database.Paginate(page.Page, page.Size)).Order("id DESC").Find(&users).Error ginx.RenderPage(c, err, page, users, total) } ``` The snippet above is condensed; the full example (delay-queue `Push`, the `middleware.TraceIDField` log helper, and more) lives in [example/tata/cmd/server/main.go](example/tata/cmd/server/main.go). The [example](example) directory also ships minimal, self-contained per-component demos (run with `go run .` inside each): [quickstart](example/quickstart) (minimal startup), [web](example/web) (validation / error codes / pagination / built-in middlewares), [db](example/db) (sqlite wiring and transactions, zero external services), [cache](example/cache) (redis commands / distributed lock / delay queue, requires local redis), [cron](example/cron) (scheduled jobs and snowflake IDs), [trace](example/trace) (distributed tracing), and [telemetry](example/telemetry) (Prometheus metrics and pprof profiling). Boot loads config by convention: it scans `./` for yaml files prefixed with `config` and merges them in filename order. The corresponding layout and config files: ``` tata/ ├── cmd/server/main.go # entrypoint ├── config.yaml # server (HTTP) + log + cron + trace sections ├── config-database.yaml # database (mysql) + redis sections └── logs/ # log output directory ``` ```yaml # config.yaml server: host: 127.0.0.1 port: 8483 mode: release # debug/release/test (default release) health_check_path: /healthz # liveness probe route (default /healthz): 200 while the process lives ready_check_path: /readyz # readiness probe route (default /readyz): 503 when not ready / draining telemetry: # telemetry endpoints (omit to disable) metrics: true # mounts /metrics (Prometheus) and collects latency/QPS namespace: "" # metric name prefix (default empty; set to the service name when multiple services share one Prometheus) buckets: [0.005, 0.01, 0.05, 0.1, 0.5, 1, 5] # latency histogram buckets in seconds (default DefBuckets) pprof: true # mounts /debug/pprof/* cors: # presence of this node enables CORS (omit to disable) allow_origins: ["*"] rate_limit: # presence of this node enables rate limiting (omit to disable) limit: 100 # max requests per window (default 100) window: 1s # statistics window (default 1s) shutdown_timeout: 5s # max wait for graceful shutdown (default 5s) drain_delay: 1s # drain on shutdown: readiness flips to 503, wait for the LB to deregister log: level: debug # debug/info/warn/error (default info) format: console # console | json filename: logs/app.log error_filename: logs/app-error.log # separate file for error and above (empty disables; same rotation policy as the main file) maxSize: 100 # MB per file before rotation maxAge: 30 # days to keep old logs maxBackups: 10 # number of old logs to keep compress: true # gzip old logs console: true # also log to the console cron: # cron jobs (see the cron package) timezone: Asia/Shanghai with_seconds: false # true for 6-field (seconds) expressions; default is 5-field "min hour day month weekday" skip_if_busy: false # skip a tick if the previous run is still going (anti-pileup for slow tasks) trace: # distributed tracing (see the trace package; takes over the X-Request-Id convention) service_name: tata # service name (default basic-go); tracing backends aggregate by service protocol: grpc # OTLP export protocol: grpc (default, 4317) | http (4318) endpoint: 127.0.0.1:4317 # collector address (defaults to the local port per protocol) secure: false # TLS-encrypted connection (default false, plaintext; always enable in production) sample_ratio: 1.0 # sampling ratio 0.0~1.0 (default full sampling) ``` ```yaml # config-database.yaml database: host: 127.0.0.1 port: 3306 user: root password: "123456" db: tata charset: utf8mb4 logger_level: warn # SQL log level (default warn) max_open_conns: 100 # max open connections redis: host: 127.0.0.1 port: 6379 password: "123456" db: 1 # timeout / pool / lock configs fall back to defaults when omitted ``` Inside `Run`, startup follows a fixed order: scan and load config -> logging init -> component wiring (`Wire`, components Init in order) -> `Init` hook -> route registration -> the HTTP server blocks. On Ctrl+C / kill it shuts down in reverse: readiness flips to 503 first and waits `drain_delay` for the LB to deregister (drain on shutdown, optionally deregistering actively via the `OnDrain` hook) -> HTTP drains (in-flight requests complete) -> the `Close` hook releases business components -> `Wire` components release in reverse (trace, wired first, closes last) -> logs flush -> the file watcher stops. Business-specific logic (e.g. a delay queue) is orchestrated in the `Init` / `Close` hooks; long-running non-HTTP components (background consumers, etc.) may also go through [lifecycle](lifecycle), sharing the same shutdown sequence as the main flow. Each module works independently of app (e.g. a pure background program may use just config + logger); see each package's README. ## Design Conventions All modules follow a consistent style — learn one and you know them all: - **Convention over configuration**: the [app](app) bootstrap scans `config`-prefixed files by convention and drives the startup/shutdown flow — zero config to run, and every convention is overridable via `Boot` fields - **One-line component wiring**: infrastructure components (database / cache / trace / snowflake / cron) ship uniform `NewBoot` adapters wired one per line in the `Wire` hook — components Init in order, Close in reverse, with auto-rollback on failure; adapters match the app structurally (zero imports on either side) - **Global injection**: connection resources (`database.DB()` / `cache.Client()`) are initialized in `main` and injected globally, so business code passes no parameters - **Unified response convention**: [ginx](ginx) renders a uniform `{code, msg, data}` envelope, and [errcode](errcode) codes map automatically to 4xx/5xx (e.g. `errcode.ErrNotFound` → HTTP 404 + `{"code":10404}`) - **Config as object**: all config structs carry `yaml` / `toml` / `json` / `mapstructure` tags, working with [config](config)'s `UnmarshalWithDefault` and the `default` tag for zero-value fallbacks - **Import on demand**: optional drivers (database's mysql / postgres / sqlite) live in separate sub-packages; anything not imported stays out of the dependency graph - **Layered docs**: each package's `README.md` provides usage and configuration details; each package's `doc.go` provides package-level API docs, viewable on [pkg.go.dev](https://pkg.go.dev) once pulled ## Directory Structure ``` basic-go/ ├── app/ Application bootstrap: config -> logging -> component wiring (Wire) -> resources -> HTTP in one entry ├── cache/ Redis access: basic commands + distributed locks + delay queue ├── config/ Config loading: defaults / env / files / hot reload ├── cron/ Cron jobs: cron-expression scheduling, panic auto-recover ├── database/ Database access: unified gorm wrapper + transaction helper + pagination, drivers on demand │ ├── mysql/ │ ├── postgres/ │ └── sqlite/ ├── errcode/ Business error codes: "ten-thousands + HTTP status" codes, uniform {code,msg,data} responses ├── example/ Usage examples: minimal per-component demos (quickstart/web/db/cache/cron/trace/telemetry) + the tata full-stack integration ├── ginx/ Web service: gin config-driven startup + centralized route management │ └── middleware/ Built-in middlewares: CORS / rate limiting / TraceID / binding validation / telemetry, usable standalone with raw gin ├── lifecycle/ App lifecycle: graceful start/stop + signal handling ├── logger/ Logging: zap + lumberjack, dedicated error-level file ├── snowflake/ Snowflake IDs: trend-increasing unique IDs, clock-rollback protection └── trace/ Distributed tracing: OpenTelemetry + OTLP (gRPC/HTTP), spans bridged to the X-Request-Id logging convention ``` ## Contributing 1. Fork this repository 2. Create a `Feat_xxx` branch 3. Commit your changes 4. Create a Pull Request