Skip to content

Latest commit

 

History

History
153 lines (112 loc) · 4.35 KB

File metadata and controls

153 lines (112 loc) · 4.35 KB

go-ext

go-ext is a compact toolkit for building HTTP services in Go. It provides configuration management, structured logging, a lightweight REST framework based on Gin, and database initialization helpers for GORM (MySQL and SQLite).

Key Features

  • Configuration management

    • Supports multiple formats (YAML, JSON, TOML) and environment variables with the ext prefix (e.g. EXT_SERVER_BINDADDR)
    • Uses mapstructure for structured custom configuration
    • Built-in validation and functional options for flexible initialization
  • Structured logging

    • Built on Go's log/slog with optional file rotation via lumberjack
    • Automatically extracts OpenTelemetry trace/span IDs when available
    • Supports multiple levels (Debug, Info, Warn, Error, Fatal)
    • Configurable output format (text or json) and output target (stdout or file)
  • RESTful utilities

    • Built with Gin for high-performance HTTP APIs
    • Middleware support for tracing and metrics
  • Storage helpers

    • Provides a GORM-based NewDB initializer (returns (*gorm.DB, error)) for MySQL and SQLite
    • Connection pool configuration (MaxIdleConns, MaxOpenConns)

Installation

go get github.com/fize/go-ext

Quick Start

Database initialization

Use the configuration helpers in the config package and create a GORM *gorm.DB via the storage package:

import (
    "github.com/fize/go-ext/config"
    "github.com/fize/go-ext/storage"
)

cfg, err := config.NewSQLConfig(
    config.WithType("mysql"),
    config.WithHost("localhost:3306"),
    config.WithUser("root"),
    config.WithPassword("password"),
    config.WithDB("myapp"),
)
if err != nil {
    panic(err)
}

db, err := storage.NewDB(cfg)
if err != nil {
    panic(err)
}
// Use db.WithContext(ctx).Create(&model) etc.

Configuration Loading

import "github.com/fize/go-ext/config"

cfg := config.NewConfig()
if err := cfg.Load("config.yaml", false); err != nil {
    panic(err)
}

Server (New Instance Mode)

import "github.com/fize/go-ext/ginserver"

cfg := config.NewConfig()
cfg.Server.BindAddr = ":8080"

server, err := ginserver.NewServer(cfg)
if err != nil {
    panic(err)
}

server.Engine.GET("/ping", func(c *gin.Context) {
    c.JSON(200, gin.H{"message": "pong"})
})

// Run with graceful shutdown
ctx, cancel, err := server.RunWithContext()
if err != nil {
    panic(err)
}
defer cancel()

Logging

Use the logging helpers provided by the log package (package-level helpers and a default logger):

import "github.com/fize/go-ext/log"

log.Info("Starting application...")
log.Debug("Connected to database", "db", "myapp")

Testing

Run unit tests with:

go test ./...

Notes

  • The storage package exposes a NewDB initializer that returns (*gorm.DB, error) for better error handling.
  • The config package's Load() method now returns error instead of panicking.
  • The ginserver package introduces a new Server instance mode with NewServer() for better multi-service support.
  • Response/request helpers previously provided by the ginserver package have been removed; projects should define their own API request/response formats.

Breaking Changes (v2)

  1. config.BaseConfig.Load() - now returns error
  2. storage.NewDB() - now returns (*gorm.DB, error)
  3. ginserver.InitGinServer() - now returns (*gin.Engine, *log.Logger, error)

If you want help migrating code, check the _example directory for updated examples.

Examples

A set of small runnable examples is provided under the _example directory:

  • ./_example/config — demonstrates loading configuration from testdata/config.yaml and parsing custom sections.
  • ./_example/log — shows basic usage of the default logger and context-aware logging.
  • ./_example/ginserver — minimal RestController example registered with the RestfulAPI.
  • ./_example/middleware — demonstrates attaching GinLogger and GinRecovery middleware to a Gin engine.
  • ./_example/storage — creates an in-memory SQLite *gorm.DB via storage.NewDB.
  • ./_example/server — demonstrates the new Server instance mode with graceful shutdown.

Run an example with go run, for example:

go run ./_example/ginserver
go run ./_example/server

Note: some examples start HTTP servers and will block the terminal. Use separate terminals or build binaries with go build if needed.