AdapterFile

AdapterFile is the default configuration management implementation in the framework, based on file loading and reading.

Use through g.Cfg Singleton Object

In most scenarios, we can conveniently use the file-based configuration management implementation through the g.Cfg singleton object already encapsulated by the framework. For example:

config.yaml

  1. server:
  2. address: ":8888"
  3. openapiPath: "/api.json"
  4. swaggerPath: "/swagger"
  5. dumpRouterMap: false
  6. database:
  7. default:
  8. link: "mysql:root:12345678@tcp(127.0.0.1:3306)/test"
  9. debug: true

main.go

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/os/gctx"
  6. )
  7. func main() {
  8. var ctx = gctx.New()
  9. fmt.Println(g.Cfg().MustGet(ctx, "server.address").String())
  10. fmt.Println(g.Cfg().MustGet(ctx, "database.default").Map())
  11. }

After running, the terminal output:

  1. :8888
  2. map[debug:true link:mysql:root:12345678@tcp(127.0.0.1:3306)/test]

Use via gcfg.NewWithAdapter

We can also create a configuration management object based on a given Adapter via the configuration component’s NewWithAdapter method. Here, we provide an AdapterFile interface object.

config.yaml

  1. server:
  2. address: ":8888"
  3. openapiPath: "/api.json"
  4. swaggerPath: "/swagger"
  5. dumpRouterMap: false
  6. database:
  7. default:
  8. link: "mysql:root:12345678@tcp(127.0.0.1:3306)/test"
  9. debug: true

main.go

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/os/gcfg"
  5. "github.com/gogf/gf/v2/os/gctx"
  6. )
  7. func main() {
  8. var ctx = gctx.New()
  9. adapter, err := gcfg.NewAdapterFile("config")
  10. if err != nil {
  11. panic(err)
  12. }
  13. config := gcfg.NewWithAdapter(adapter)
  14. fmt.Println(config.MustGet(ctx, "server.address").String())
  15. fmt.Println(config.MustGet(ctx, "database.default").Map())
  16. }

After running, the terminal output:

  1. :8888
  2. map[debug:true link:mysql:root:12345678@tcp(127.0.0.1:3306)/test]