conf

package
v0.0.0-...-36d29c1 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2024 License: Apache-2.0 Imports: 11 Imported by: 0

README

项目的配置管理

程序需要有默认配置

用户拿到你这个程序后,是可以不做配置直接运行, 只要当需要配置的时候才进配置

你的程序需要达到一个基础的可用性, 至少有默认配置

config

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// [mysql]
	MySQL *MySQL `json:"mysql" toml:"mysql"`
	// [http]
	Http *Http `json:"http" toml:"http"`
}

程序的配置对象 config --> object

func C

func C() *Config

把全局对象保护起来

func DefaultConfig

func DefaultConfig() *Config

func LoadConfigFromEnv

func LoadConfigFromEnv() (*Config, error)

通过环境变量读取配置 采用第三方库: "github.com/caarlos0/env/v6" 读取环境变量 环境变量 ---> config object

func LoadConfigFromToml

func LoadConfigFromToml(path string) (*Config, error)

toml 文件加载 使用到的第三方库: "github.com/BurntSushi/toml"

func (*Config) String

func (c *Config) String() string

Stringer is implemented by any value that has a String method, which defines the “native” format for that value. The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer // such as Print.

type Stringer interface {
	String() string
}

格式化成一个json

type Http

type Http struct {
	Host string `json:"host" toml:"host" env:"HTTP_HOST"`
	Port int    `json:"port" toml:"port" env:"HTTP_PORT"`
}

func (*Http) Address

func (h *Http) Address() string

type MySQL

type MySQL struct {
	Host     string `json:"host" toml:"host"`
	Port     int    `json:"port" toml:"port"`
	DB       string `json:"db" toml:"db"`
	Username string `json:"username" toml:"username"`
	Password string `json:"password" toml:"password"`

	// 高级参数
	MaxOpenConn int `toml:"max_open_conn" env:"MYSQL_MAX_OPEN_CONN"`
	MaxIdleConn int `toml:"max_idle_conn" env:"MYSQL_MAX_IDLE_CONN"`
	MaxLifeTime int `toml:"max_life_time" env:"MYSQL_MAX_LIFE_TIME"`
	MaxIdleTime int `toml:"max_idle_time" env:"MYSQL_MAX_IDLE_TIME"`
	// contains filtered or unexported fields
}

host = "127.0.0.1" port = 3306 db = "vblog" username = "admin" password = "123456"

func (*MySQL) GetConnPool

func (m *MySQL) GetConnPool() (*sql.DB, error)

获取连接池对象, 驱动: _ "github.com/go-sql-driver/mysql" 适配标准库: sql.DB, 连接池(在驱动层之上)

func (*MySQL) ORM

func (m *MySQL) ORM() *gorm.DB

go mod tidy gorm官方文档 https://gorm.io/docs/connecting_to_the_database.html 这里的*gorm.DB 是一个单列实例 ORM DB 已经封装了sql.DB(标准库), 这个对象有很多高阶配置,比如 最大连接说, 活跃连接数 直接操作Obj -ORM-> DB

Jump to

Keyboard shortcuts

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