goconfig

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2024 License: Apache-2.0 Imports: 25 Imported by: 2

README

go-config

go-config is characterized by daily work requirements and extension development, encapsulated generic tool classes

stable license download release commit issues pull fork star go size contributors codecov Go Report Card Go Reference Sourcegraph

介绍

go 开发中常用的一些配置

安装
go mod init "go-config-examples"
go get -u github.com/kamalyes/go-config
go mod tidy
例子
package main

import (
	"context"
	"fmt"
	"log"
	"math/rand"
	"os"
	"path/filepath"
	"runtime"
	"time"

	goconfig "github.com/kamalyes/go-config"
	"github.com/kamalyes/go-config/pkg/env"
)

// generateRandomConfigContent 生成随机配置内容
func generateRandomConfigContent(moduleName string) string {
	ip := fmt.Sprintf("192.168.1.%d", rand.Intn(256))   // 随机生成 IP 地址
	port := rand.Intn(10000) + 1000                     // 随机端口范围 1000-10999
	serviceName := fmt.Sprintf("%s-server", moduleName) // 服务名称
	contextPath := fmt.Sprintf("/%s", moduleName)       // 服务根路径

	return fmt.Sprintf(`# 服务实例配置
server:
    # 服务绑定的IP
    host: "%s"
    # 端口
    port: '%d'
    # 服务名称
    service-name: "%s"
    # 服务根路径
    context-path: "%s"
    # 是否开启请求方式检测
    handle-method-not-allowed: true
    # 数据库类型
    data-driver: 'mysql'

# consul 注册中心
consul:
    # 注册中心地址
    addr: 127.0.0.1:8500
    # 间隔 单位秒
    register-interval: 30

# 其他配置...
`, ip, port, serviceName, contextPath)
}

// createConfigFile 创建配置文件并写入内容
func createConfigFile(configOptions *goconfig.ConfigOptions) error {
	content := generateRandomConfigContent(configOptions.EnvValue.String()) // 生成随机配置内容
	// 确保目录存在
	filename := fmt.Sprintf("%s/%s%s.%s", configOptions.ConfigPath, configOptions.EnvValue, configOptions.ConfigSuffix, configOptions.ConfigType)
	dir := filepath.Dir(filename)                         // 获取文件目录
	if err := os.MkdirAll(dir, os.ModePerm); err != nil { // 创建目录
		return err
	}

	// 写入内容到文件
	return os.WriteFile(filename, []byte(content), 0644) // 写入配置文件
}

// printConfig 打印配置为 JSON 格式,并包含调用者信息
func printConfig(config interface{}, caller string) {
	log.Printf("Config in format from %s: %#v", caller, config) // 打印配置内容
}

// getCallerName 获取调用者的函数名称
func getCallerName() string {
	pc, _, _, ok := runtime.Caller(1) // 获取调用者信息
	if !ok {
		return "unknown" // 如果获取失败,返回 unknown
	}
	fn := runtime.FuncForPC(pc) // 获取函数信息
	if fn == nil {
		return "unknown" // 如果函数信息为空,返回 unknown
	}
	return fn.Name() // 返回函数名称
}

// simpleUse 简单例子
func simpleUse() *goconfig.SingleConfig {
	ctx := context.Background()                                     // 创建上下文
	customManager, err := goconfig.NewSingleConfigManager(ctx, nil) // 创建单个配置管理器
	if err != nil {
		log.Fatalf("simpleUse NewSingleConfigManager  err %s", err) // 错误处理
	}
	err = createConfigFile(&customManager.Options) // 创建配置文件
	if err != nil {
		log.Fatalf("simpleUse Error creating file %#v", err) // 错误处理
	}
	config := customManager.GetConfig()  // 获取配置
	printConfig(config, getCallerName()) // 打印配置
	return config
}

// customUse 自定义环境变量、读取配置
func customUse() *goconfig.SingleConfig {
	customEnv := env.EnvironmentType("custom_single")        // 定义自定义环境类型
	customContextKey := env.ContextKey("TEST_SINGLE_CONFIG") // 定义自定义上下文键
	env.NewEnvironment().
		SetCheckFrequency(1 * time.Second) // 初始化检测时间

	configOptions := &goconfig.ConfigOptions{
		ConfigSuffix:  "_config",            // 配置后缀
		ConfigPath:    "./custom_resources", // 配置路径
		ConfigType:    "yaml",               // 配置类型
		EnvValue:      customEnv,            // 环境变量值
		EnvContextKey: customContextKey,     // 环境变量Key
	}

	err := createConfigFile(configOptions) // 创建配置文件
	if err != nil {
		log.Fatalf("customUse Error creating file %#v", err) // 错误处理
	}
	ctx := context.Background()                                               // 创建上下文
	customManager, err := goconfig.NewSingleConfigManager(ctx, configOptions) // 创建单个配置管理器
	if err != nil {
		log.Fatalf("customUse NewSingleConfigManager err %s", err) // 错误处理
	}
	config := customManager.GetConfig()  // 获取配置
	printConfig(config, getCallerName()) // 打印配置
	return config
}

func main() {
	simpleUse() // 调用简单使用示例
	customUse() // 调用自定义使用示例
}

目录结构
├── internal/    # 仅供本项目使用的库代码
├── tests/       # 测试文件
├── go.mod       # Go Modules 文件
├── resources/   # 多配置文件相关配置(建议命名如下,目前提供了一个example_config.yaml可参考)
│   ├── dev_config.yaml    # 开发环境配置文件
│   ├── sit_config.yaml    # 功能测试环境配置文件
│   └── uat_config.yaml    # 产品验收测试环境配置文件
│   └── fat_config.yaml    # 预留环境配置文件
│   └── pro_config.yaml    # 生产环境配置文件
│   └── env_custom.yaml    # 当然还通过了个性化配置文件需要结合ConfigManager一起使用
└── pkg/          # 可供其他项目使用的库代码
    ├── captcha/  # 验证码图片尺寸配置
    ├── register/ # 注册中心、服务端口等相关配置
    ├── cors/     # 跨域配置
    ├── database/ # 数据库配置
    ├── elk/      # ELK配置
    ├── email/    # 邮件配置
    ├── env/      # 环境变量配置
    ├── ftp/      # 文件服务器配置
    ├── jwt/      # JWT token 生成和校验配置
    ├── mqtt/     # MQTT 物联网配置
    ├── oss/      # OSS 配置
    ├── queue/    # mqtt等队列相关配置
    ├── pay/      # 支付相关配置(支付宝和微信)
    ├── redis/    # redis(redis缓存数据库相关配置)
    ├── sms/      # 短信配置
    ├── sts/      # STS 配置
    ├── youzan/   # 有赞配置
    └── zap/      # 日志相关配置
    └── zero/     # zero相关配置

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetModuleByName added in v0.3.1

func GetModuleByName[T any](modules []T, moduleName string) (T, error)

GetModuleByName 使用泛型来获取模块

Types

type ConfigOptions added in v0.3.2

type ConfigOptions struct {
	ConfigType    string              // 配置文件类型
	ConfigPath    string              // 配置文件路径
	ConfigSuffix  string              // 配置文件后缀
	EnvValue      env.EnvironmentType // 初始化环境
	EnvContextKey env.ContextKey      // 环境上下文Key
	UseEnvLevel   EnvLevel            // 使用环境级别,值为 "os" 或 "ctx"
}

ConfigOptions 定义配置选项结构体

func GetDefaultConfigOptions added in v0.4.3

func GetDefaultConfigOptions() *ConfigOptions

GetDefaultConfigOptions 返回 ConfigOptions 的默认值

type EnvLevel added in v0.4.4

type EnvLevel string
const (
	EnvLevelOS  EnvLevel = "os"
	EnvLevelCtx EnvLevel = "ctx"
)

type MultiConfig added in v0.3.5

type MultiConfig struct {
	Server        []register.Server     `mapstructure:"server"       yaml:"server"       json:"server"`
	Cors          []cors.Cors           `mapstructure:"cors"         yaml:"cors"         json:"cors"`
	Consul        []register.Consul     `mapstructure:"consul"       yaml:"consul"       json:"consul"`
	Captcha       []captcha.Captcha     `mapstructure:"captcha"      yaml:"captcha"      json:"captcha"`
	MySQL         []database.MySQL      `mapstructure:"mysql"        yaml:"mysql"        json:"mysql"`
	PostgreSQL    []database.PostgreSQL `mapstructure:"postgre"      yaml:"postgre"      json:"postgre"`
	SQLite        []database.SQLite     `mapstructure:"sqlite"       yaml:"sqlite"       json:"sqlite"`
	Redis         []redis.Redis         `mapstructure:"redis"        yaml:"redis"        json:"redis"`
	Email         []email.Email         `mapstructure:"email"        yaml:"email"        json:"email"`
	Ftp           []ftp.Ftp             `mapstructure:"ftp"          yaml:"ftp"          json:"ftp"`
	JWT           []jwt.JWT             `mapstructure:"jwt"          yaml:"jwt"          json:"jwt"`
	Minio         []oss.Minio           `mapstructure:"minio"        yaml:"minio"        json:"minio"`
	AliyunOss     []oss.AliyunOss       `mapstructure:"aliyunoss"    yaml:"aliyunoss"    json:"aliyunoss"`
	Mqtt          []queue.Mqtt          `mapstructure:"mqtt"         yaml:"mqtt"         json:"mqtt"`
	Zap           []zap.Zap             `mapstructure:"zap"          yaml:"zap"          json:"zap"`
	AliPay        []pay.AliPay          `mapstructure:"alipay"       yaml:"alipay"       json:"alipay"`
	WechatPay     []pay.WechatPay       `mapstructure:"wechatpay"    yaml:"wechatpay"    json:"wechatpay"`
	AliyunSms     []sms.AliyunSms       `mapstructure:"aliyunsms"    yaml:"aliyunsms"    json:"aliyunsms"`
	AliyunSts     []sts.AliyunSts       `mapstructure:"aliyunsts"    yaml:"aliyunsts"    json:"aliyunsts"`
	Youzan        []youzan.YouZan       `mapstructure:"youzan"       yaml:"youzan"       json:"youzan"`
	ZeroServer    []zero.RpcServer      `mapstructure:"zeroserver"   yaml:"zeroserver"   json:"zeroserver"`
	ZeroClient    []zero.RpcClient      `mapstructure:"zeroclient"   yaml:"zeroclient"   json:"zeroclient"`
	ZeroRestful   []zero.Restful        `mapstructure:"zerorestful"  yaml:"zerorestful"  json:"zerorestful"`
	Kafka         []elk.Kafka           `mapstructure:"kafka"        yaml:"kafka"        json:"kafka"`
	Elasticsearch []elk.Elasticsearch   `mapstructure:"elasticsearch"  yaml:"elasticsearch"  json:"elasticsearch"`
	Jaeger        []register.Jaeger     `mapstructure:"jaeger"       yaml:"jaeger"       json:"jaeger"`
	Viper         *viper.Viper          `mapstructure:"-"            yaml:"-"            json:"-"`
}

MultiConfig 多配置

type MultiConfigManager added in v0.4.2

type MultiConfigManager struct {
	MultiConfig *MultiConfig
	Options     ConfigOptions
}

MultiConfigManager 负责加载和管理 MultiConfig

func NewMultiConfigManager added in v0.4.2

func NewMultiConfigManager(ctx context.Context, options *ConfigOptions) (*MultiConfigManager, error)

NewMultiConfigManager 创建一个新的 MultiConfigManager

func (*MultiConfigManager) GetConfig added in v0.4.2

func (m *MultiConfigManager) GetConfig() *MultiConfig

GetConfig 获取 MultiConfig 配置

func (*MultiConfigManager) SubItem added in v0.4.2

func (m *MultiConfigManager) SubItem(ctx context.Context, subKey string, v interface{})

SubItem 从配置中获取指定的配置子项

type SingleConfig added in v0.3.5

type SingleConfig struct {
	Server        register.Server     `mapstructure:"server"       yaml:"server"       json:"server"`
	Cors          cors.Cors           `mapstructure:"cors"         yaml:"cors"         json:"cors"`
	Consul        register.Consul     `mapstructure:"consul"       yaml:"consul"       json:"consul"`
	Captcha       captcha.Captcha     `mapstructure:"captcha"      yaml:"captcha"      json:"captcha"`
	MySQL         database.MySQL      `mapstructure:"mysql"        yaml:"mysql"        json:"mysql"`
	PostgreSQL    database.PostgreSQL `mapstructure:"postgre"      yaml:"postgre"      json:"postgre"`
	SQLite        database.SQLite     `mapstructure:"sqlite"       yaml:"sqlite"       json:"sqlite"`
	Redis         redis.Redis         `mapstructure:"redis"        yaml:"redis"        json:"redis"`
	Email         email.Email         `mapstructure:"email"        yaml:"email"        json:"email"`
	Ftp           ftp.Ftp             `mapstructure:"ftp"          yaml:"ftp"          json:"ftp"`
	JWT           jwt.JWT             `mapstructure:"jwt"          yaml:"jwt"          json:"jwt"`
	Minio         oss.Minio           `mapstructure:"minio"        yaml:"minio"        json:"minio"`
	AliyunOss     oss.AliyunOss       `mapstructure:"aliyunoss"    yaml:"aliyunoss"    json:"aliyunoss"`
	Mqtt          queue.Mqtt          `mapstructure:"mqtt"         yaml:"mqtt"         json:"mqtt"`
	Zap           zap.Zap             `mapstructure:"zap"          yaml:"zap"          json:"zap"`
	AliPay        pay.AliPay          `mapstructure:"alipay"       yaml:"alipay"       json:"alipay"`
	WechatPay     pay.WechatPay       `mapstructure:"wechatpay"    yaml:"wechatpay"    json:"wechatpay"`
	AliyunSms     sms.AliyunSms       `mapstructure:"aliyunsms"    yaml:"aliyunsms"    json:"aliyunsms"`
	AliyunSts     sts.AliyunSts       `mapstructure:"aliyunsts"    yaml:"aliyunsts"    json:"aliyunsts"`
	Youzan        youzan.YouZan       `mapstructure:"youzan"       yaml:"youzan"       json:"youzan"`
	ZeroServer    zero.RpcServer      `mapstructure:"zeroserver"   yaml:"zeroserver"   json:"zeroserver"`
	ZeroClient    zero.RpcClient      `mapstructure:"zeroclient"   yaml:"zeroclient"   json:"zeroclient"`
	ZeroRestful   zero.Restful        `mapstructure:"zerorestful"  yaml:"zerorestful"  json:"zerorestful"`
	Kafka         elk.Kafka           `mapstructure:"kafka"        yaml:"kafka"        json:"kafka"`
	Elasticsearch elk.Elasticsearch   `mapstructure:"elasticsearch"  yaml:"elasticsearch"  json:"elasticsearch"`
	Jaeger        register.Jaeger     `mapstructure:"jaeger"       yaml:"jaeger"       json:"jaeger"`
	Viper         *viper.Viper        `mapstructure:"-"            yaml:"-"            json:"-"`
}

SingleConfig 单一配置

func GetSingleConfigByModuleName added in v0.4.0

func GetSingleConfigByModuleName(multiConfig MultiConfig, moduleName string) (*SingleConfig, error)

GetSingleConfigByModuleName 根据提供的模块名称从 MultiConfig 中获取对应的 SingleConfig

type SingleConfigManager added in v0.4.2

type SingleConfigManager struct {
	SingleConfig *SingleConfig
	Options      ConfigOptions
}

SingleConfigManager 负责加载和管理 SingleConfig

func NewSingleConfigManager added in v0.4.2

func NewSingleConfigManager(ctx context.Context, options *ConfigOptions) (*SingleConfigManager, error)

NewSingleConfigManager 创建一个新的 SingleConfigManager

func (*SingleConfigManager) GetConfig added in v0.4.2

func (m *SingleConfigManager) GetConfig() *SingleConfig

GetConfig 获取 SingleConfig 配置

Directories

Path Synopsis
* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-07 23:55:15 * @FilePath: \go-config\internal\common.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-07 23:55:15 * @FilePath: \go-config\internal\common.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
pkg
database
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-03 20:55:05 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-07 23:50:15 * @FilePath: \go-config\pkg\database\common.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-03 20:55:05 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-07 23:50:15 * @FilePath: \go-config\pkg\database\common.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
elk
* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-07 23:59:11 * @FilePath: \go-config\pkg\elk\es.go * @Description: * * Copyright (j) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-07 23:59:11 * @FilePath: \go-config\pkg\elk\es.go * @Description: * * Copyright (j) 2024 by kamalyes, All Rights Reserved.
env
* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-07 16:11:10 * @FilePath: \go-config\pkg\env\env.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-07 16:11:10 * @FilePath: \go-config\pkg\env\env.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
ftp
* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-03 20:31:10 * @FilePath: \go-config\pkg\ftp\ftp.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-03 20:31:10 * @FilePath: \go-config\pkg\ftp\ftp.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
jwt
oss
pay
sms
* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-07 23:53:49 * @FilePath: \go-config\pkg\sms\aliyun.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2023-07-28 00:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-07 23:53:49 * @FilePath: \go-config\pkg\sms\aliyun.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
sts
zap
zero
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-07 15:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-07 19:55:50 * @FilePath: \go-config\pkg\zero\etcd.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-07 15:50:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-07 19:55:50 * @FilePath: \go-config\pkg\zero\etcd.go * @Description: * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

Jump to

Keyboard shortcuts

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