9

Go里优雅的使用全局配置

 3 years ago
source link: https://jiajunhuang.com/articles/2021_03_18-go_config.md.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Go里优雅的使用全局配置

全局配置是一个单例,最简单的实现是使用一个全局变量,为了到处都可以使用到,所以常见的做法是有一个包,例如名字叫 global 或者诸如此类的,然后要用到的地方去导入,例如:

package handlers

import (
    "log"

    "github.com/jiajunhuang/demo/global"
)

func Ping() {
    log.Printf("%s", global.Config.RedisURL)
}

不过这样写起来挺麻烦的,所以,不如这样写。首先咱们照样有一个包,叫做 singleton,里面就有 Config 的单例方法:

package singleton

import (
	"sync"

	"github.com/kelseyhightower/envconfig"
)

var (
	config      *Config
	configMutex sync.Mutex
)

type Config struct {
	Debug bool   `envconfig:"debug"`
	DBURL string `envconfig:"db_url"`
}

func GetConfig() *Config {
	if config != nil {
		return config
	}

	configMutex.Lock()
	defer configMutex.Unlock()

	// double check
	if config != nil {
		return config
	}

	config = &Config{}
	envconfig.Process("APP_NAME", &config)

	return config
}

于是,咱们就可以这样使用了:

package main

import (
    "github.com/jiajunhuang/demo/singleton"
)

func main() {
    // init config
	_ = singleton.GetConfig()

}

在别的包里,可以这样:

package handlers

import (
    "github.com/jiajunhuang/demo/singleton"
)

var (
	config = singleton.GetConfig()
)

func Haha() {
    println(config.DBURL)
}

若要问我区别,其实没啥太大的区别,只不过呢,写起来更简单了,只要写 config.Blabla 而不是 global.Config.Blabla

就是这样!


微信公众号
关注公众号,获得及时更新

StackGuard的作用

Go DiskQueue源码阅读

NSQ源码分析

NSQ简明教程

结合Redis与MySQL实现又快又好的数据方案

程序员的MySQL手册(五):索引优化

程序员的MySQL手册(四):索引设计

程序员的MySQL手册(三):数据库设计

Linux窗口管理器下的截图

Go设计模式:facade模式和观察者模式

程序员的MySQL手册(二): 监控与benchmark

Go设计模式: 责任链模式

我们真的需要这么复杂的技术栈吗?

Go设计模式:装饰器模式

程序员的MySQL手册(一): 安装,基本配置




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK