dongmi5020 2018-03-27 13:41
浏览 12
已采纳

如何处理多个配置

Is there a good way to reuse the code to read different configurations?

btw: I used config lib is configor

the code maybe like,

type Config1 struct {
    //some config items
}
type Config2 struct {
    //some config items
}

func LoadConfig1() Config1 {
    var c Config1
    configor.Load(&c, "MY/CONFIG1/PATH")
    return c
}

func LoadConfig1() Config2 {
    var c Config2
    configor.Load(&c, "MY/CONFIG2/PATH")
    return c
}
  1. Can I reuse LoadConfig with Config1/Config2?
  2. Can I design an object like singleton to create Config1/Config2 just once.
  • 写回答

2条回答 默认 最新

  • duanjiao6735 2018-03-27 14:27
    关注

    Use the sync package to make sure config is only loaded once.

    Example:

    import "sync"
    
    var (
        c Config1
        once sync.Once
        loadFunc = func() {
            configor.Load(&c, "MY/CONFIG1/PATH")
        }
    )
    
    func LoadConfig() Config1 {
        once.Do(loadFunc)
        return c
    }
    

    Any subsequent calls to LoadConfig will be ignored. For example:

    func main() {
        c1 := LoadConfig() // Loaded, returns the value
        c2 := LoadConfig() // Not loaded, returns the first loaded value
        c3 := LoadConfig() // Not loaded, returns the first loaded value
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 算能的sail库的运用
  • ¥15 'Content-Type': 'application/x-www-form-urlencoded' 请教 这种post请求参数,该如何填写??重点是下面那个冒号啊
  • ¥15 找代写python里的jango设计在线书店
  • ¥15 请教如何关于Msg文件解析
  • ¥200 sqlite3数据库设置用户名和密码
  • ¥15 AutoDL无法使用docker install吗?
  • ¥15 cups交叉编译后移植到tina sdk的t113,只需要实现usb驱动打印机,打印pdf文件
  • ¥30 关于#wireshark#的问题:需要网络应用流量数据集需要做长度序列的实验,需要与应用产生的会话的数据包的长度,如视频类或者聊天类软件
  • ¥15 根据上述描述表示泥浆密度沿着管路的长度方向在不断变化,如何来表示泥浆密度随管路的变化(标签-matlab|关键词-流计算)
  • ¥21 matlab可以把图像数据转换为小波分析吗