jcbaseGo

package module
v0.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 8, 2025 License: MIT Imports: 15 Imported by: 1

README

jcbaseGo

一个功能丰富的 Go 语言基础工具包,提供多种可复用的组件和工具函数,帮助开发者快速构建高质量的 Go 应用程序。

🚀 功能特性

  • 🔐 安全组件: SM4/AES 加密、密码处理、数据验证
  • 🗄️ 数据库 ORM: MySQL/SQLite 支持,基于 GORM 的抽象层
  • 📧 邮件服务: 支持 SMTP 邮件发送
  • 📁 附件管理: 本地、FTP、SFTP、OSS、COS 等多种存储方式
  • 🛠️ 工具函数: 类型转换、字符串处理、JSON 操作等
  • 💾 缓存支持: Redis 缓存组件
  • ✅ 数据验证: 邮箱、手机号、身份证、URL 等验证
  • 🎛️ 配置管理: 支持 JSON、INI、命令行等多种配置源

📦 安装

go get github.com/jcbowen/jcbaseGo

🏗️ 项目结构

jcbaseGo/
├── component/                   # 核心组件目录
│   ├── attachment/             # 附件管理组件
│   │   ├── attachment.go       # 附件管理主文件
│   │   ├── method.go           # 附件操作方法
│   │   └── remote/             # 远程存储实现
│   │       ├── cos.go          # 腾讯云 COS
│   │       ├── ftp.go          # FTP 存储
│   │       ├── oss.go          # 阿里云 OSS
│   │       ├── sftp.go         # SFTP 存储
│   │       └── remote.go       # 远程存储接口
│   ├── helper/                 # 工具函数集合
│   │   ├── convert.go          # 类型转换工具
│   │   ├── file.go             # 文件操作工具
│   │   ├── json.go             # JSON 处理工具
│   │   ├── money.go            # 金额处理工具
│   │   ├── ssh.go              # SSH 工具
│   │   ├── string.go           # 字符串处理工具
│   │   └── util.go             # 通用工具函数
│   ├── mailer/                 # 邮件发送组件
│   │   └── mailer.go
│   ├── orm/                    # 数据库 ORM 抽象层
│   │   ├── instance.go         # 数据库实例接口
│   │   ├── mysql/              # MySQL 实现
│   │   └── sqlite/             # SQLite 实现
│   ├── redis/                  # Redis 缓存组件
│   │   ├── cache.go
│   │   └── main.go
│   ├── security/               # 安全相关功能
│   │   ├── aes.go              # AES 加密
│   │   ├── base.go             # 安全基础功能
│   │   ├── password.go         # 密码处理
│   │   ├── safe.go             # 安全工具
│   │   └── sm4.go              # SM4 加密
│   ├── trait/                  # Trait 模式实现
│   │   ├── controller/         # 控制器基础功能
│   │   └── crud/               # CRUD 操作模板
│   ├── tlsconfig/              # TLS 配置
│   │   └── tlsconfig.go
│   ├── upgrade/                # 升级工具
│   │   └── main.go
│   └── validator/              # 数据验证组件
│       └── main.go
├── config.go                   # 配置管理
├── type.go                     # 全局类型定义
├── errcode/                    # 错误码定义
│   └── errcode.go
├── example/                    # 使用示例
│   ├── README.md               # 示例说明文档
│   ├── security/               # 安全组件示例
│   ├── helper/                 # 工具函数示例
│   ├── orm/                    # 数据库示例
│   ├── mailer/                 # 邮件示例
│   ├── redis/                  # Redis 示例
│   ├── validator/              # 验证器示例
│   └── attachment/             # 附件管理示例
├── middleware/                 # 中间件
│   └── main.go
├── go.mod                      # Go 模块文件
└── LICENSE                     # 许可证文件

🎯 快速开始

1. 安全加密
package main

import (
    "fmt"
    "github.com/jcbowen/jcbaseGo/component/security"
    "github.com/jcbowen/jcbaseGo/component/helper"
)

func main() {
    // SM4 加密
    sm4 := security.SM4{
        Text: "Hello, SM4!",
        Key:  "1234567890123456",
        Iv:   "abcdefghijklmnop",
        Mode: "CBC",
    }

    var cipherText string
    err := sm4.Encrypt(&cipherText)
    if err != nil {
        panic(err)
    }
    fmt.Printf("加密结果: %s\n", cipherText)

    // AES 加密
    aes := security.AES{
        Text: "Hello, AES!",
        Key:  "1234567890123456",
        Iv:   "abcdefghijklmnop",
    }

    err = aes.Encrypt(&cipherText)
    if err != nil {
        panic(err)
    }
    fmt.Printf("AES 加密结果: %s\n", cipherText)
}
2. 数据库操作
package main

import (
    "github.com/jcbowen/jcbaseGo"
    "github.com/jcbowen/jcbaseGo/component/orm/mysql"
)

func main() {
    // 配置数据库连接
    config := jcbaseGo.DbStruct{
        Host:     "localhost",
        Port:     "3306",
        Username: "root",
        Password: "password",
        Dbname:   "test_db",
        Charset:  "utf8mb4",
    }

    // 连接数据库
    db := mysql.New(config)
    gormDB := db.GetDb()

    // 使用 GORM 进行数据库操作
    // ... 数据库操作代码
}
3. 邮件发送
package main

import (
    "github.com/jcbowen/jcbaseGo/component/mailer"
)

func main() {
    // 配置邮件服务
    mailer := mailer.Mailer{
        Host:     "smtp.example.com",
        Port:     587,
        Username: "your-email@example.com",
        Password: "your-password",
    }

    // 发送邮件
    err := mailer.Send("recipient@example.com", "测试邮件", "这是一封测试邮件")
    if err != nil {
        panic(err)
    }
}

📚 组件说明

🔐 安全组件 (security/)
  • SM4: 国密 SM4 对称加密算法,支持 CBC 和 GCM 模式
  • AES: AES 对称加密算法,支持 16/24/32 字节密钥
  • 密码处理: 密码哈希、验证等安全功能
🗄️ 数据库 ORM (orm/)
  • MySQL: 基于 GORM 的 MySQL 数据库操作
  • SQLite: SQLite 数据库支持
  • 事务支持: 完整的事务操作支持
  • 连接池: 自动连接池管理
📧 邮件服务 (mailer/)
  • SMTP 支持: 标准 SMTP 协议支持
  • TLS/SSL: 安全连接支持
  • 附件支持: 邮件附件功能
  • 模板支持: HTML 邮件模板
📁 附件管理 (attachment/)
  • 本地存储: 本地文件系统存储
  • FTP: FTP 服务器存储
  • SFTP: SFTP 安全文件传输
  • OSS: 阿里云对象存储
  • COS: 腾讯云对象存储
🛠️ 工具函数 (helper/)
  • 类型转换: 各种数据类型之间的转换
  • 字符串处理: 字符串截取、替换、分割等
  • JSON 操作: JSON 序列化和反序列化
  • 文件操作: 文件读写、目录操作
  • 金额处理: 货币计算和格式化
  • SSH 工具: SSH 连接和操作
💾 缓存支持 (redis/)
  • Redis 连接: Redis 数据库连接管理
  • 缓存操作: 键值对存储和检索
  • 过期时间: 自动过期管理
  • 连接池: 连接池优化
✅ 数据验证 (validator/)
  • 邮箱验证: 标准邮箱格式验证
  • 手机号验证: 中国大陆手机号验证
  • 身份证验证: 15位和18位身份证验证
  • URL 验证: URL 格式验证
  • IP 地址验证: IPv4/IPv6 地址验证

🎨 设计模式

Trait 模式

项目使用 Trait 模式提供可复用的行为:

// CRUD Trait 提供基础的增删改查操作
type UserController struct {
    trait.CRUD
}

// 自动获得 Create、Read、Update、Delete 方法
配置驱动

支持多种配置源:

// JSON 配置
config := jcbaseGo.Config{
    Source: "config.json",
}

// INI 配置
config := jcbaseGo.Config{
    Source: "config.ini",
}

// 环境变量
config := jcbaseGo.Config{
    Source: "env",
}

📖 使用示例

详细的使用示例请查看 example/ 目录:

# 运行 SM4 加密示例
go run example/security/sm4/main.go

# 运行 AES 加密示例
go run example/security/aes/main.go

# 运行数据库示例
go run example/orm/mysql/main.go

# 运行邮件发送示例
go run example/mailer/main.go

🧪 测试

运行测试:

# 运行所有测试
go test ./...

# 运行特定组件测试
go test ./component/security/ -v
go test ./component/helper/ -v

📋 依赖要求

  • Go 1.23.0+
  • MySQL 5.7+ (可选)
  • Redis 6.0+ (可选)

🤝 贡献

欢迎提交 Issue 和 Pull Request!

贡献指南
  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 打开 Pull Request
代码规范
  • 使用简体中文注释
  • 遵循 Go 语言编码规范
  • 添加适当的测试用例
  • 更新相关文档

📄 许可证

本项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情。

🙏 致谢

感谢所有为这个项目做出贡献的开发者!

📞 联系方式


⭐ 如果这个项目对你有帮助,请给它一个星标!

Documentation

Index

Constants

View Source
const (
	ConfigTypeJSON    = "json"    // 配置类型:json文件
	ConfigTypeINI     = "ini"     // 配置类型:ini文件
	ConfigTypeCommand = "command" // 配置类型:通过命令行传递的字符串json

	// ConfigTypeFile 文件类型,根据文件后缀自动识别是json还是ini文件
	// Deprecated: 推荐使用ConfigTypeJSON或者ConfigTypeINI,保留仅为了兼容旧版
	ConfigTypeFile = "file"
)

Variables

View Source
var Config interface{}

Config 实例化后配置信息将储存在此全局变量中

Functions

func PanicIfError added in v0.6.1

func PanicIfError(err interface{})

PanicIfError 异常处理 如果err不为nil,则直接panic,用于省略if判断

Types

type AttachmentStruct added in v0.6.1

type AttachmentStruct struct {
	StorageType string `json:"storage_type" default:"local"`   // 存储类型 local/ftp/sftp/cos/oss
	LocalDir    string `json:"local_dir" default:"attachment"` // 本地附件目录,默认为 attachment

	// 附件访问域名
	// 配置后以配置为准,不配置则初始化中自动赋值,一定以“/”结尾
	// 如果配置了远程附件,则此处为远程附件访问域名,否则为本地附件访问域名
	VisitDomain string `json:"visit_domain" default:"/"`
	// 本地附件访问域名,不管是否配置远程附件
	// 配置后以配置为准,不配置则初始化中自动赋值,一定以“/”结尾
	LocalVisitDomain string `json:"local_visit_domain" default:"/"`
}

AttachmentStruct 附件配置

type COSStruct added in v0.8.0

type COSStruct struct {
	SecretId  string `json:"secretId" default:""`  // 腾讯云Cos SecretId
	SecretKey string `json:"secretKey" default:""` // 腾讯云Cos SecretKey
	Bucket    string `json:"bucket" default:""`    // 腾讯云Cos Bucket
	Region    string `json:"region" default:""`    // 腾讯云Cos Region
	Url       string `json:"url" default:""`       // 腾讯云Cos Url

	// 自定义附件访问域名(非平台配置,供程序调用,非必填,一定以“/”结尾)
	CustomizeVisitDomain string `json:"customize_visit_domain" default:""`
}

COSStruct cos配置

type DbStruct added in v0.2.1

type DbStruct struct {
	DriverName    string `json:"driverName" default:"mysql"`   // 驱动类型
	Protocol      string `json:"protocol" default:"tcp"`       // 协议
	Host          string `json:"host" default:"localhost"`     // 数据库地址
	Port          string `json:"port" default:"3306"`          // 数据库端口号
	Dbname        string `json:"dbname" default:"dbname"`      // 表名称
	Username      string `json:"username" default:"root"`      // 用户名
	Password      string `json:"password" default:""`          // 密码
	Charset       string `json:"charset" default:"utf8mb4"`    // 编码
	TablePrefix   string `json:"tablePrefix" default:""`       // 表前缀
	ParseTime     string `json:"parseTime" default:"False"`    // 是否开启时间解析
	SingularTable bool   `json:"singularTable" default:"true"` // 使用单数表名
	Alias         string `json:"alias" default:"db"`           // 配置信息别名
}

DbStruct 数据库配置

type DefaultConfigStruct added in v0.6.1

type DefaultConfigStruct struct {
	Db         DbStruct         `json:"db"`         // 数据库配置信息
	Redis      RedisStruct      `json:"redis"`      // redis配置信息
	Attachment AttachmentStruct `json:"attachment"` // 附件配置信息
	Oss        OSSStruct        `json:"oss"`        // oss配置信息
	Cos        COSStruct        `json:"cos"`        // cos配置信息
	Project    ProjectStruct    `json:"project"`    // 项目配置信息
	Repository RepositoryStruct `json:"repository"` // 仓库配置信息
}

DefaultConfigStruct 默认配置信息结构 一般情况下推荐自定义,不想自定义的情况下可以采用默认结构

type FTPStruct added in v0.8.0

type FTPStruct struct {
	Address  string        `json:"address" default:""`           // FTP服务器地址
	Username string        `json:"username" default:""`          // FTP登录用户名
	Password string        `json:"password" default:""`          // FTP登录密码
	Timeout  time.Duration `json:"timeout,omitempty" default:""` // 连接超时时间,可选

	// 自定义附件访问域名(非平台配置,供程序调用,非必填,一定以“/”结尾)
	CustomizeVisitDomain string `json:"customize_visit_domain" default:""`
}

type ListData added in v0.7.1

type ListData struct {
	List     interface{} `json:"list"`
	Total    int         `json:"total"`
	Page     int         `json:"page"`
	PageSize int         `json:"page_size"`
}

ListData 分页查询数据输出

type MailerStruct added in v0.6.1

type MailerStruct struct {
	Host     string `json:"host" default:"smtp.qq.com"`        // 邮箱地址
	Port     string `json:"port" default:"465"`                // 邮箱端口号
	Username string `json:"username" default:"example@qq.com"` // 邮箱用户名
	Password string `json:"password" default:"123456"`         // 邮箱密码
	From     string `json:"from" default:"example@qq.com"`     // 发件邮箱
	UseTLS   bool   `json:"useTls" default:"true"`             // 是否使用TLS
	CertPath string `json:"cert_path" default:""`              // 证书文件路径
	KeyPath  string `json:"key_path" default:""`               // 私钥文件路径
	CAPath   string `json:"ca_path" default:""`                // CA证书文件路径
}

MailerStruct 发送邮箱配置

type MysqlBaseModel added in v0.7.1

type MysqlBaseModel struct {
}

MysqlBaseModel gorm基础模型

func (*MysqlBaseModel) BeforeCreate added in v0.7.1

func (b *MysqlBaseModel) BeforeCreate(tx *gorm.DB) (err error)

func (*MysqlBaseModel) BeforeUpdate added in v0.7.1

func (b *MysqlBaseModel) BeforeUpdate(tx *gorm.DB) (err error)

func (*MysqlBaseModel) ConfigAlias added in v0.7.1

func (b *MysqlBaseModel) ConfigAlias() string

func (*MysqlBaseModel) ModelParse added in v0.7.1

func (b *MysqlBaseModel) ModelParse(modelType reflect.Type) (tableName string, fields []string)

type OSSStruct added in v0.8.0

type OSSStruct struct {
	AccessKeyId     string `json:"AccessKeyId" default:""`     // 阿里云访问密钥ID
	AccessKeySecret string `json:"AccessKeySecret" default:""` // 阿里云访问密钥Secret
	Endpoint        string `json:"endpoint" default:""`        // 阿里云OSS的Endpoint
	BucketName      string `json:"bucketName" default:""`      // 阿里云OSS存储桶名称

	// 自定义附件访问域名(非平台配置,供程序调用,非必填,一定以“/”结尾)
	CustomizeVisitDomain string `json:"customize_visit_domain" default:""`
}

OSSStruct oss配置

type Option added in v0.6.1

type Option struct {
	ConfigType   string      `json:"config_type" default:"file"`              // 配置类型,仅支持:json、ini、file、command
	ConfigSource string      `json:"config_source" default:"./data/conf.ini"` // 配置源(json文件/ini文件/命令行)
	ConfigData   interface{} `json:"config_data"`                             // 配置信息
	RuntimePath  string      `json:"runtime_path" default:"/runtime/"`        // 运行缓存目录
}

Option jcbaseGo配置选项

func New added in v0.3.1

func New(opt Option) *Option

New 初始化配置

func (*Option) ConfigToStruct added in v0.6.1

func (opt *Option) ConfigToStruct(configStruct interface{})

ConfigToStruct 将 Option.ConfigData 赋值到自定义结构体中

func (*Option) GetConfig added in v0.6.1

func (opt *Option) GetConfig() *interface{}

GetConfig 获取配置信息 返回配置数据的指针,调用者需要确保配置数据不为空

func (*Option) GetConfigOption added in v0.6.1

func (opt *Option) GetConfigOption() Option

GetConfigOption 获取配置选项

type ProjectStruct added in v0.6.1

type ProjectStruct struct {
	Name string `json:"name" default:"jcbaseGo"` // 项目名称
}

ProjectStruct 项目配置

type RedisStruct added in v0.2.1

type RedisStruct struct {
	Host     string `json:"host" default:"localhost"` // redis地址
	Port     string `json:"port" default:"6379"`      // redis端口号
	Password string `json:"password" default:""`      // redis密码
	Db       string `json:"db" default:"0"`           // redis数据库
}

RedisStruct redis配置

type RepositoryStruct added in v0.2.1

type RepositoryStruct struct {
	Dir        string `json:"dir" default:"./project/app/"`                            // 本地仓库目录
	Branch     string `json:"branch" default:"master"`                                 // 远程仓库分支
	RemoteName string `json:"remoteName" default:"origin"`                             // 远程仓库名称
	RemoteURL  string `json:"remoteURL" default:"git@github.com:jcbowen/jcbaseGo.git"` // 远程仓库地址
}

RepositoryStruct 仓库配置

type Result added in v0.7.1

type Result struct {
	Code    int         `json:"code" default:"200"`
	Message string      `json:"message" default:"success"`
	Data    interface{} `json:"data,omitempty"`
	Total   *int        `json:"total,omitempty"`
}

Result 响应结构

type SFTPStruct added in v0.8.0

type SFTPStruct struct {
	Address    string        `json:"address" default:""`           // SFTP服务器地址
	Username   string        `json:"username" default:""`          // SFTP登录用户名
	Password   string        `json:"password" default:""`          // SFTP登录密码
	PrivateKey []byte        `json:"private_key" default:""`       // SFTP登录私钥
	Timeout    time.Duration `json:"timeout,omitempty" default:""` // 连接超时时间,可选

	// 自定义附件访问域名(非平台配置,供程序调用,非必填,一定以“/”结尾)
	CustomizeVisitDomain string `json:"customize_visit_domain" default:""`
}

SFTPStruct sftp配置

type SQLLiteBaseModel added in v0.7.1

type SQLLiteBaseModel struct {
}

SQLLiteBaseModel gorm基础模型

func (*SQLLiteBaseModel) BeforeCreate added in v0.7.1

func (b *SQLLiteBaseModel) BeforeCreate(tx *gorm.DB) (err error)

func (*SQLLiteBaseModel) BeforeUpdate added in v0.7.1

func (b *SQLLiteBaseModel) BeforeUpdate(tx *gorm.DB) (err error)

func (*SQLLiteBaseModel) ConfigAlias added in v0.7.1

func (b *SQLLiteBaseModel) ConfigAlias() string

func (*SQLLiteBaseModel) ModelParse added in v0.7.1

func (b *SQLLiteBaseModel) ModelParse(modelType reflect.Type) (tableName string, fields []string)

type SSLStruct added in v0.6.1

type SSLStruct = WebServer

SSLStruct ssl配置

type SqlLiteStruct added in v0.6.1

type SqlLiteStruct struct {
	DbFile        string `json:"dbFile" default:"./db/jcbaseGo.db"` // 数据库文件
	TablePrefix   string `json:"tablePrefix" default:"jc_"`         // 表前缀
	SingularTable bool   `json:"singularTable" default:"true"`      // 使用单数表名
	Alias         string `json:"alias" default:"main"`              // 配置信息别名
}

SqlLiteStruct sqlite配置

type WebServer added in v0.9.1

type WebServer struct {
	Port      int    `json:"port" ini:"port" default:"8080"`              // web服务端口号
	EnableSSL bool   `json:"enable_ssl" ini:"enable_ssl" default:"false"` // 是否启用ssl
	CertPath  string `json:"cert_path" ini:"cert_path" default:""`        // ssl证书路径
	KeyPath   string `json:"key_path" ini:"key_path" default:""`          // ssl密钥路径
}

WebServer web服务配置

Directories

Path Synopsis
component
attachment/remote
Package remote 提供多种远程存储方式的统一接口。
Package remote 提供多种远程存储方式的统一接口。
orm
php
example
attachment/ftp command
helper/convert command
helper/string command
mailer command
orm/mysql command
security/aes command
security/sm4 command
validator command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL