go-zero/core/conf
2025-01-14 23:16:13 +08:00
..
config_test.go fix/conf_multi_layer_map (#4407) 2024-10-05 04:46:32 +00:00
config.go chore: code format (#4572) 2025-01-14 23:16:13 +08:00
options.go fix golint issues in core/conf (#476) 2021-02-18 15:56:19 +08:00
properties_test.go chore: add more tests (#3279) 2023-05-24 23:58:45 +08:00
properties.go fix: conf anonymous overlay problem (#2847) 2023-02-05 14:40:57 +08:00
readme.md optimize: shedding algorithm performance (#3908) 2024-02-15 20:22:22 +08:00

How to use

  1. Define a config structure, like below:
type RestfulConf struct {
  ServiceName  string        `json:",env=SERVICE_NAME"`  // read from env automatically
	Host         string        `json:",default=0.0.0.0"`
	Port         int
	LogMode      string        `json:",options=[file,console]"`
	Verbose      bool          `json:",optional"`
	MaxConns     int           `json:",default=10000"`
	MaxBytes     int64         `json:",default=1048576"`
	Timeout      time.Duration `json:",default=3s"`
	CpuThreshold int64         `json:",default=900,range=[0:1000)"`
}
  1. Write the yaml, toml or json config file:
  • yaml example
# most fields are optional or have default values
port: 8080
logMode: console
# you can use env settings
maxBytes: ${MAX_BYTES}
  • toml example
# most fields are optional or have default values
port = 8_080
logMode = "console"
# you can use env settings
maxBytes = "${MAX_BYTES}"
  1. Load the config from a file:
// exit on error
var config RestfulConf
conf.MustLoad(configFile, &config)

// or handle the error on your own
var config RestfulConf
if err := conf.Load(configFile, &config); err != nil {
  log.Fatal(err)
}

// enable reading from environments
var config RestfulConf
conf.MustLoad(configFile, &config, conf.UseEnv())