Skip to content

Instantly share code, notes, and snippets.

@ismdeep
Created December 28, 2022 08:01
Show Gist options
  • Save ismdeep/4d75f3303d255da3d68399babe72c941 to your computer and use it in GitHub Desktop.
Save ismdeep/4d75f3303d255da3d68399babe72c941 to your computer and use it in GitHub Desktop.
golang load config
package main
type Config struct {
Server struct {
Bind string `config:"default:0.0.0.0:9000;env:CONFIG_SERVER_BIND"`
Mode string `config:"default:debug;env:CONFIG_SERVER_MODE"`
}
}
var Data Config
func Load(v interface{}) error {
// TODO
return nil
}
func main() {
if err := Load(&Data); err != nil {
panic(err)
}
}
@ismdeep
Copy link
Author

ismdeep commented Dec 28, 2022

Hi, I got a new method of configuration load in golang. As the code show, it allows programmer to set label "config" to describe default value and load value from environment name. But I don't know how to implement it.

It would be very thankful to help me out with TODO part.

@chrisfarms
Copy link

envconfig does this, might meet your needs

@NekoTashi
Copy link

NekoTashi commented Dec 28, 2022

type Config struct {
        Bind string `env:"CONFIG_SERVER_BIND,default=0.0.0.0:9000"`
        Mode string `env:"CONFIG_SERVER_MODE,default=debug"`
}

func New() (*Config, error) {
	var config Config

	if err := envconfig.Process(context.Background(), &config); err != nil {
		return nil, fmt.Errorf("error getting var envs: %w", err)
	}

	return &config, nil
}

@ismdeep
Copy link
Author

ismdeep commented Dec 28, 2022

envconfig does this, might meet your needs

Thanks, that's awesome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment