一個簡單的go語言配置文件庫,將YAML配置自動映射到實體中, 相似與spring-boot配置文件。 會從根實體strut遍歷實體屬性,若是類型爲bool, string, 整型, 浮點型,map[string]interface{},[]interface{}, 則會根據tag中的profile
值(不設置則爲當前屬性名的首字母變小寫)解析YAML或flag或環境變量,並賦值; 若YAML或flag或環境變量都不存在,則使用tag中的profileDefault
設置默認值; 若默認值也未設置,則返回error。默認變量優先級:環境變量 > flag參數 > YAML > profileDefault默認值, 能夠經過設置envHigher未false,讓flag優先級 > 環境變量。 注意:接收類型和返回類型都須要爲指針類型。git
eureka:
instance:
preferIpAddress: true
leaseRenewalIntervalInSeconds: 10
leaseExpirationDurationInSeconds: 30
client:
serviceUrl:
defaultZone: http://localhost:8000/eureka/
registryFetchIntervalSeconds: 10
logging:
level:
github.com/flyleft/consul-iris/pkg/config: info
github.com/flyleft/consul-iris/pkg/route: debug
複製代碼
type SingleEnv struct {
Eureka SingleEureka
Logging map[string]interface{} `profile:"logging.level" profileDefault:"{\"github.com/flyleft/consul-iris\":\"debug\"}"`
}
type SingleEureka struct {
PreferIpAddress bool `profile:"instance.preferIpAddress"`
LeaseRenewalIntervalInSeconds int32 `profile:"instance.leaseRenewalIntervalInSeconds"`
LeaseExpirationDurationInSeconds uint `profile:"instance.leaseExpirationDurationInSeconds"`
ServerDefaultZone string `profile:"client.serviceUrl.defaultZone" profileDefault:"http://localhost:8000/eureka/"`
RegistryFetchIntervalSeconds byte `profile:"client.registryFetchIntervalSeconds"`
}
//使用
func main() {
env, err := Profile(&SingleEnv{}, "test-single-profile.yml", true)
if err != nil {
t.Error("Profile execute error", err)
}
trueEnv := env.(*SingleEnv)
}
//經過環境變量覆蓋配置,好比設置EUREKA_INSTANCE_LEASERENEWALINTERVALINSECONDS環境變量值覆蓋eureka.instance.leaseRenewalIntervalInSeconds
複製代碼
profiles:
active: dev # 設置生效的profile
dev:
database:
username: root
password: root
eureka:
zone: http://localhost:8000/eureka/
fetchInterval: 10
logging:
level:
github.com/flyleft/consul-iris/pkg/config: info
github.com/flyleft/consul-iris/pkg/route: debug
production:
database:
username: production
password: production
eureka:
zone: http://localhost:8000/eureka/
fetchInterval: 10
logging:
level:
github.com/flyleft/consul-iris/pkg/config: info
github.com/flyleft/consul-iris/pkg/route: debug
複製代碼
type Eureka struct {
Zone string `profile:"zone"`
FetchInterval int `profile:"fetchInterval"`
}
type DataSource struct {
Host string `profile:"host" profileDefault:"localhost"`
Username string `profile:"username"`
Password string `profile:"password"`
}
type MultiEnv struct {
DataSource DataSource `profile:"database"`
Eureka Eureka
Logging map[string]interface{} `profile:"logging.level" profileDefault:"{\"github.com/flyleft/consul-iris\":\"debug\"}"`
Users []interface{} `profile:"users" profileDefault:"[\"admin\",\"test\",\"root\"]"`
}
func main() {
env, err := Profile(&MultiEnv{}, "test-multi-profile.yml", true)
if err != nil {
t.Error("Profile execute error", err)
}
trueEnv := env.(*MultiEnv)
}
//可經過環境變量DEV_EUREKA_ZONE覆蓋eureka.zone的值
複製代碼