1
0
mirror of https://github.com/go-kratos/kratos.git synced 2025-01-10 00:29:01 +02:00
kratos/examples/config/main.go
2021-05-17 21:52:23 +08:00

54 lines
958 B
Go

package main
import (
"flag"
"log"
"github.com/go-kratos/kratos/v2/config"
"github.com/go-kratos/kratos/v2/config/file"
)
var flagconf string
func init() {
flag.StringVar(&flagconf, "conf", "config.yaml", "config path, eg: -conf config.yaml")
}
func main() {
flag.Parse()
c := config.New(
config.WithSource(
file.NewSource(flagconf),
),
)
if err := c.Load(); err != nil {
panic(err)
}
// struct
var v struct {
Serivce struct {
Name string `json:"name"`
Version string `json:"version"`
} `json:"service"`
}
if err := c.Scan(&v); err != nil {
panic(err)
}
log.Printf("config: %+v", v)
// key/value
name, err := c.Value("service.name").String()
if err != nil {
panic(err)
}
log.Printf("service: %s", name)
// watch key
if err := c.Watch("service.name", func(key string, value config.Value) {
log.Printf("config changed: %s = %v\n", key, value)
}); err != nil {
panic(err)
}
<-make(chan struct{})
}