Files
go-common/README.md

3.8 KiB
Raw Blame History

GoCommon - Go通用工具类库

这是一个Go语言开发的通用工具类库为其他Go项目提供常用的工具方法集合。

功能模块

1. 数据库迁移工具 (migration)

提供数据库迁移功能支持MySQL、PostgreSQL、SQLite等数据库。

2. 日期转换工具 (datetime)

提供日期时间转换功能,支持时区设定和多种格式转换。

3. HTTP Restful工具 (http)

提供HTTP请求/响应处理工具包含标准化的响应结构、分页支持和HTTP状态码与业务状态码的分离。

4. 中间件工具 (middleware)

提供常用的HTTP中间件包括CORS处理和时区管理。

5. 配置工具 (config)

提供从外部文件加载配置的功能支持数据库、OSS、Redis、CORS、MinIO等配置。

6. 存储工具 (storage)

提供文件上传和查看功能支持OSS和MinIO两种存储方式并提供HTTP处理器。

7. 邮件工具 (email)

提供SMTP邮件发送功能支持纯文本和HTML邮件使用Go标准库实现。

8. 短信工具 (sms)

提供阿里云短信发送功能支持模板短信和批量发送使用Go标准库实现。

安装

go get github.com/go-common

使用示例

详细的使用说明请参考各模块的文档:

快速示例

数据库迁移

import "github.com/go-common/migration"

migrator := migration.NewMigrator(db)
migrator.AddMigration(migration.Migration{
    Version: "20240101000001",
    Description: "create_users_table",
    Up: func(db *gorm.DB) error {
        return db.Exec("CREATE TABLE users ...").Error
    },
})
migrator.Up()

日期转换

import "github.com/go-common/datetime"

datetime.SetDefaultTimeZone(datetime.AsiaShanghai)
now := datetime.Now()
str := datetime.FormatDateTime(now)

HTTP响应

import "github.com/go-common/http"

http.Success(w, data)
http.SuccessPage(w, list, total, page, pageSize)
http.Error(w, 1001, "业务错误")

中间件

import (
    "github.com/go-common/middleware"
    "github.com/go-common/http"
)

// CORS + 时区中间件
chain := middleware.NewChain(
    middleware.CORS(),
    middleware.Timezone,
)
handler := chain.ThenFunc(yourHandler)

// 在处理器中获取时区
timezone := http.GetTimezone(r)

配置管理

import "github.com/go-common/config"

// 从文件加载配置
cfg, err := config.LoadFromFile("./config.json")

// 获取各种配置
dsn, _ := cfg.GetDatabaseDSN()
redisAddr := cfg.GetRedisAddr()
corsConfig := cfg.GetCORS()

文件上传和查看

import "github.com/go-common/storage"

// 创建存储实例
storage, _ := storage.NewStorage(storage.StorageTypeOSS, cfg)

// 创建上传处理器
uploadHandler := storage.NewUploadHandler(storage.UploadHandlerConfig{
    Storage: storage,
    MaxFileSize: 10 * 1024 * 1024,
    AllowedExts: []string{".jpg", ".png"},
})

// 创建代理查看处理器
proxyHandler := storage.NewProxyHandler(storage)

邮件发送

import "github.com/go-common/email"

// 从配置创建邮件发送器
mailer, _ := email.NewEmail(cfg.GetEmail())

// 发送邮件
mailer.SendSimple(
    []string{"recipient@example.com"},
    "主题",
    "正文",
)

短信发送

import "github.com/go-common/sms"

// 从配置创建短信发送器
smsClient, _ := sms.NewSMS(cfg.GetSMS())

// 发送短信
smsClient.SendSimple(
    []string{"13800138000"},
    map[string]string{"code": "123456"},
)

更多示例请查看 examples 目录。

版本

v1.0.0