Configuration File

Overview

Normally started with a static configuration file to load configurations. The go-zero configuration currently supports various formats. This chapter will demonstrate how go-zero will load static configurations.

Task Targets

  1. Learn how to define a configuration.
  2. Load configuration from static file.

Preparing

  1. Complete golang installation

Define Config

  1. type Config struct {
  2. Name string
  3. Host string `json:",default=0.0.0.0"`
  4. Port int
  5. }

As above, we defined a Config struct, which contains several fields, service name, listener addresses, port number.

Define configuration path

  1. var f = flag.String("f", "config.yaml", "config file")

We generally want to specify the path to the configuration file at startup, so we have a flag path to accept the configuration file.

Write configuration

We use yaml as an instance to generate config.yaml files.Write the following

  1. Name: demo
  2. Host: 127.0.0.1
  3. Port: 6370

Load Configuration

  1. flag.Parse()
  2. var c Config
  3. conf.MustLoad(*f, &c)
  4. println(c.Name)

Here the configuration file in config.yaml is loaded into Config file.We can then use our configuration variable in the program

Full Instance

  1. package main
  2. import (
  3. "flag"
  4. "github.com/zeromicro/go-zero/core/conf"
  5. )
  6. type Config struct {
  7. Name string
  8. Host string `json:",default=0.0.0.0"`
  9. Port int
  10. }
  11. var f = flag.String("f", "config.yaml", "config file")
  12. func main() {
  13. flag.Parse()
  14. var c Config
  15. conf.MustLoad(*f, &c)
  16. println(c.Name)
  17. }