Relax ZeroC
Relax ZeroC

Reputation: 683

How to handle multiple config

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.

Upvotes: 0

Views: 133

Answers (2)

Lansana Camara
Lansana Camara

Reputation: 9873

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
}

Upvotes: 2

Himanshu
Himanshu

Reputation: 12675

Above code will not work. It will throw an error saying

LoadConfig redeclared in this block

Because

Go does not allow to create function with same name. We can create method with same name having different receivers.

Create receiver for config1 and config2 with same method name.

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

func (config1 *Config1) LoadConfig() {
    configor.Load(config1, "MY/CONFIG1/PATH")
}

func (config2 *Config2) LoadConfig() {
    configor.Load(config2, "MY/CONFIG2/PATH")
}

For creating an object each time you can create a function to check if instance already exists like that.

type Config1 struct {
}

var instance *Config1

func GetInstance() *Config1 {
    if instance == nil {
        instance = &Config1{}   // <--- NOT THREAD SAFE
    }
    return instance
}

Upvotes: 1

Related Questions