1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-21 21:40:55 +00:00

remove config API's context parameter

This commit is contained in:
Ming Deng 2020-10-13 22:32:41 +08:00
parent 568626cd57
commit 2572094a8d
22 changed files with 457 additions and 497 deletions

View File

@ -15,8 +15,6 @@
package adapter package adapter
import ( import (
context2 "context"
"github.com/astaxie/beego/adapter/session" "github.com/astaxie/beego/adapter/session"
newCfg "github.com/astaxie/beego/core/config" newCfg "github.com/astaxie/beego/core/config"
"github.com/astaxie/beego/server/web" "github.com/astaxie/beego/server/web"
@ -74,54 +72,54 @@ type beegoAppConfig struct {
} }
func (b *beegoAppConfig) Set(key, val string) error { func (b *beegoAppConfig) Set(key, val string) error {
if err := b.innerConfig.Set(context2.Background(), BConfig.RunMode+"::"+key, val); err != nil { if err := b.innerConfig.Set(BConfig.RunMode+"::"+key, val); err != nil {
return b.innerConfig.Set(context2.Background(), key, val) return b.innerConfig.Set(key, val)
} }
return nil return nil
} }
func (b *beegoAppConfig) String(key string) string { func (b *beegoAppConfig) String(key string) string {
if v, err := b.innerConfig.String(context2.Background(), BConfig.RunMode+"::"+key); v != "" && err != nil { if v, err := b.innerConfig.String(BConfig.RunMode + "::" + key); v != "" && err != nil {
return v return v
} }
res, _ := b.innerConfig.String(context2.Background(), key) res, _ := b.innerConfig.String(key)
return res return res
} }
func (b *beegoAppConfig) Strings(key string) []string { func (b *beegoAppConfig) Strings(key string) []string {
if v, err := b.innerConfig.Strings(context2.Background(), BConfig.RunMode+"::"+key); len(v) > 0 && err != nil { if v, err := b.innerConfig.Strings(BConfig.RunMode + "::" + key); len(v) > 0 && err != nil {
return v return v
} }
res, _ := b.innerConfig.Strings(context2.Background(), key) res, _ := b.innerConfig.Strings(key)
return res return res
} }
func (b *beegoAppConfig) Int(key string) (int, error) { func (b *beegoAppConfig) Int(key string) (int, error) {
if v, err := b.innerConfig.Int(context2.Background(), BConfig.RunMode+"::"+key); err == nil { if v, err := b.innerConfig.Int(BConfig.RunMode + "::" + key); err == nil {
return v, nil return v, nil
} }
return b.innerConfig.Int(context2.Background(), key) return b.innerConfig.Int(key)
} }
func (b *beegoAppConfig) Int64(key string) (int64, error) { func (b *beegoAppConfig) Int64(key string) (int64, error) {
if v, err := b.innerConfig.Int64(context2.Background(), BConfig.RunMode+"::"+key); err == nil { if v, err := b.innerConfig.Int64(BConfig.RunMode + "::" + key); err == nil {
return v, nil return v, nil
} }
return b.innerConfig.Int64(context2.Background(), key) return b.innerConfig.Int64(key)
} }
func (b *beegoAppConfig) Bool(key string) (bool, error) { func (b *beegoAppConfig) Bool(key string) (bool, error) {
if v, err := b.innerConfig.Bool(context2.Background(), BConfig.RunMode+"::"+key); err == nil { if v, err := b.innerConfig.Bool(BConfig.RunMode + "::" + key); err == nil {
return v, nil return v, nil
} }
return b.innerConfig.Bool(context2.Background(), key) return b.innerConfig.Bool(key)
} }
func (b *beegoAppConfig) Float(key string) (float64, error) { func (b *beegoAppConfig) Float(key string) (float64, error) {
if v, err := b.innerConfig.Float(context2.Background(), BConfig.RunMode+"::"+key); err == nil { if v, err := b.innerConfig.Float(BConfig.RunMode + "::" + key); err == nil {
return v, nil return v, nil
} }
return b.innerConfig.Float(context2.Background(), key) return b.innerConfig.Float(key)
} }
func (b *beegoAppConfig) DefaultString(key string, defaultVal string) string { func (b *beegoAppConfig) DefaultString(key string, defaultVal string) string {
@ -167,13 +165,13 @@ func (b *beegoAppConfig) DefaultFloat(key string, defaultVal float64) float64 {
} }
func (b *beegoAppConfig) DIY(key string) (interface{}, error) { func (b *beegoAppConfig) DIY(key string) (interface{}, error) {
return b.innerConfig.DIY(context2.Background(), key) return b.innerConfig.DIY(key)
} }
func (b *beegoAppConfig) GetSection(section string) (map[string]string, error) { func (b *beegoAppConfig) GetSection(section string) (map[string]string, error) {
return b.innerConfig.GetSection(context2.Background(), section) return b.innerConfig.GetSection(section)
} }
func (b *beegoAppConfig) SaveConfigFile(filename string) error { func (b *beegoAppConfig) SaveConfigFile(filename string) error {
return b.innerConfig.SaveConfigFile(context2.Background(), filename) return b.innerConfig.SaveConfigFile(filename)
} }

View File

@ -15,8 +15,6 @@
package config package config
import ( import (
"context"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/astaxie/beego/core/config" "github.com/astaxie/beego/core/config"
@ -27,148 +25,148 @@ type newToOldConfigerAdapter struct {
} }
func (c *newToOldConfigerAdapter) Set(key, val string) error { func (c *newToOldConfigerAdapter) Set(key, val string) error {
return c.delegate.Set(context.Background(), key, val) return c.delegate.Set(key, val)
} }
func (c *newToOldConfigerAdapter) String(key string) string { func (c *newToOldConfigerAdapter) String(key string) string {
res, _ := c.delegate.String(context.Background(), key) res, _ := c.delegate.String(key)
return res return res
} }
func (c *newToOldConfigerAdapter) Strings(key string) []string { func (c *newToOldConfigerAdapter) Strings(key string) []string {
res, _ := c.delegate.Strings(context.Background(), key) res, _ := c.delegate.Strings(key)
return res return res
} }
func (c *newToOldConfigerAdapter) Int(key string) (int, error) { func (c *newToOldConfigerAdapter) Int(key string) (int, error) {
return c.delegate.Int(context.Background(), key) return c.delegate.Int(key)
} }
func (c *newToOldConfigerAdapter) Int64(key string) (int64, error) { func (c *newToOldConfigerAdapter) Int64(key string) (int64, error) {
return c.delegate.Int64(context.Background(), key) return c.delegate.Int64(key)
} }
func (c *newToOldConfigerAdapter) Bool(key string) (bool, error) { func (c *newToOldConfigerAdapter) Bool(key string) (bool, error) {
return c.delegate.Bool(context.Background(), key) return c.delegate.Bool(key)
} }
func (c *newToOldConfigerAdapter) Float(key string) (float64, error) { func (c *newToOldConfigerAdapter) Float(key string) (float64, error) {
return c.delegate.Float(context.Background(), key) return c.delegate.Float(key)
} }
func (c *newToOldConfigerAdapter) DefaultString(key string, defaultVal string) string { func (c *newToOldConfigerAdapter) DefaultString(key string, defaultVal string) string {
return c.delegate.DefaultString(context.Background(), key, defaultVal) return c.delegate.DefaultString(key, defaultVal)
} }
func (c *newToOldConfigerAdapter) DefaultStrings(key string, defaultVal []string) []string { func (c *newToOldConfigerAdapter) DefaultStrings(key string, defaultVal []string) []string {
return c.delegate.DefaultStrings(context.Background(), key, defaultVal) return c.delegate.DefaultStrings(key, defaultVal)
} }
func (c *newToOldConfigerAdapter) DefaultInt(key string, defaultVal int) int { func (c *newToOldConfigerAdapter) DefaultInt(key string, defaultVal int) int {
return c.delegate.DefaultInt(context.Background(), key, defaultVal) return c.delegate.DefaultInt(key, defaultVal)
} }
func (c *newToOldConfigerAdapter) DefaultInt64(key string, defaultVal int64) int64 { func (c *newToOldConfigerAdapter) DefaultInt64(key string, defaultVal int64) int64 {
return c.delegate.DefaultInt64(context.Background(), key, defaultVal) return c.delegate.DefaultInt64(key, defaultVal)
} }
func (c *newToOldConfigerAdapter) DefaultBool(key string, defaultVal bool) bool { func (c *newToOldConfigerAdapter) DefaultBool(key string, defaultVal bool) bool {
return c.delegate.DefaultBool(context.Background(), key, defaultVal) return c.delegate.DefaultBool(key, defaultVal)
} }
func (c *newToOldConfigerAdapter) DefaultFloat(key string, defaultVal float64) float64 { func (c *newToOldConfigerAdapter) DefaultFloat(key string, defaultVal float64) float64 {
return c.delegate.DefaultFloat(context.Background(), key, defaultVal) return c.delegate.DefaultFloat(key, defaultVal)
} }
func (c *newToOldConfigerAdapter) DIY(key string) (interface{}, error) { func (c *newToOldConfigerAdapter) DIY(key string) (interface{}, error) {
return c.delegate.DIY(context.Background(), key) return c.delegate.DIY(key)
} }
func (c *newToOldConfigerAdapter) GetSection(section string) (map[string]string, error) { func (c *newToOldConfigerAdapter) GetSection(section string) (map[string]string, error) {
return c.delegate.GetSection(context.Background(), section) return c.delegate.GetSection(section)
} }
func (c *newToOldConfigerAdapter) SaveConfigFile(filename string) error { func (c *newToOldConfigerAdapter) SaveConfigFile(filename string) error {
return c.delegate.SaveConfigFile(context.Background(), filename) return c.delegate.SaveConfigFile(filename)
} }
type oldToNewConfigerAdapter struct { type oldToNewConfigerAdapter struct {
delegate Configer delegate Configer
} }
func (o *oldToNewConfigerAdapter) Set(ctx context.Context, key, val string) error { func (o *oldToNewConfigerAdapter) Set(key, val string) error {
return o.delegate.Set(key, val) return o.delegate.Set(key, val)
} }
func (o *oldToNewConfigerAdapter) String(ctx context.Context, key string) (string, error) { func (o *oldToNewConfigerAdapter) String(key string) (string, error) {
return o.delegate.String(key), nil return o.delegate.String(key), nil
} }
func (o *oldToNewConfigerAdapter) Strings(ctx context.Context, key string) ([]string, error) { func (o *oldToNewConfigerAdapter) Strings(key string) ([]string, error) {
return o.delegate.Strings(key), nil return o.delegate.Strings(key), nil
} }
func (o *oldToNewConfigerAdapter) Int(ctx context.Context, key string) (int, error) { func (o *oldToNewConfigerAdapter) Int(key string) (int, error) {
return o.delegate.Int(key) return o.delegate.Int(key)
} }
func (o *oldToNewConfigerAdapter) Int64(ctx context.Context, key string) (int64, error) { func (o *oldToNewConfigerAdapter) Int64(key string) (int64, error) {
return o.delegate.Int64(key) return o.delegate.Int64(key)
} }
func (o *oldToNewConfigerAdapter) Bool(ctx context.Context, key string) (bool, error) { func (o *oldToNewConfigerAdapter) Bool(key string) (bool, error) {
return o.delegate.Bool(key) return o.delegate.Bool(key)
} }
func (o *oldToNewConfigerAdapter) Float(ctx context.Context, key string) (float64, error) { func (o *oldToNewConfigerAdapter) Float(key string) (float64, error) {
return o.delegate.Float(key) return o.delegate.Float(key)
} }
func (o *oldToNewConfigerAdapter) DefaultString(ctx context.Context, key string, defaultVal string) string { func (o *oldToNewConfigerAdapter) DefaultString(key string, defaultVal string) string {
return o.delegate.DefaultString(key, defaultVal) return o.delegate.DefaultString(key, defaultVal)
} }
func (o *oldToNewConfigerAdapter) DefaultStrings(ctx context.Context, key string, defaultVal []string) []string { func (o *oldToNewConfigerAdapter) DefaultStrings(key string, defaultVal []string) []string {
return o.delegate.DefaultStrings(key, defaultVal) return o.delegate.DefaultStrings(key, defaultVal)
} }
func (o *oldToNewConfigerAdapter) DefaultInt(ctx context.Context, key string, defaultVal int) int { func (o *oldToNewConfigerAdapter) DefaultInt(key string, defaultVal int) int {
return o.delegate.DefaultInt(key, defaultVal) return o.delegate.DefaultInt(key, defaultVal)
} }
func (o *oldToNewConfigerAdapter) DefaultInt64(ctx context.Context, key string, defaultVal int64) int64 { func (o *oldToNewConfigerAdapter) DefaultInt64(key string, defaultVal int64) int64 {
return o.delegate.DefaultInt64(key, defaultVal) return o.delegate.DefaultInt64(key, defaultVal)
} }
func (o *oldToNewConfigerAdapter) DefaultBool(ctx context.Context, key string, defaultVal bool) bool { func (o *oldToNewConfigerAdapter) DefaultBool(key string, defaultVal bool) bool {
return o.delegate.DefaultBool(key, defaultVal) return o.delegate.DefaultBool(key, defaultVal)
} }
func (o *oldToNewConfigerAdapter) DefaultFloat(ctx context.Context, key string, defaultVal float64) float64 { func (o *oldToNewConfigerAdapter) DefaultFloat(key string, defaultVal float64) float64 {
return o.delegate.DefaultFloat(key, defaultVal) return o.delegate.DefaultFloat(key, defaultVal)
} }
func (o *oldToNewConfigerAdapter) DIY(ctx context.Context, key string) (interface{}, error) { func (o *oldToNewConfigerAdapter) DIY(key string) (interface{}, error) {
return o.delegate.DIY(key) return o.delegate.DIY(key)
} }
func (o *oldToNewConfigerAdapter) GetSection(ctx context.Context, section string) (map[string]string, error) { func (o *oldToNewConfigerAdapter) GetSection(section string) (map[string]string, error) {
return o.delegate.GetSection(section) return o.delegate.GetSection(section)
} }
func (o *oldToNewConfigerAdapter) Unmarshaler(ctx context.Context, prefix string, obj interface{}, opt ...config.DecodeOption) error { func (o *oldToNewConfigerAdapter) Unmarshaler(prefix string, obj interface{}, opt ...config.DecodeOption) error {
return errors.New("unsupported operation, please use actual config.Configer") return errors.New("unsupported operation, please use actual config.Configer")
} }
func (o *oldToNewConfigerAdapter) Sub(ctx context.Context, key string) (config.Configer, error) { func (o *oldToNewConfigerAdapter) Sub(key string) (config.Configer, error) {
return nil, errors.New("unsupported operation, please use actual config.Configer") return nil, errors.New("unsupported operation, please use actual config.Configer")
} }
func (o *oldToNewConfigerAdapter) OnChange(ctx context.Context, key string, fn func(value string)) { func (o *oldToNewConfigerAdapter) OnChange(key string, fn func(value string)) {
// do nothing // do nothing
} }
func (o *oldToNewConfigerAdapter) SaveConfigFile(ctx context.Context, filename string) error { func (o *oldToNewConfigerAdapter) SaveConfigFile(filename string) error {
return o.delegate.SaveConfigFile(filename) return o.delegate.SaveConfigFile(filename)
} }

View File

@ -24,38 +24,38 @@ import (
func TestBaseConfiger_DefaultBool(t *testing.T) { func TestBaseConfiger_DefaultBool(t *testing.T) {
bc := newBaseConfier("true") bc := newBaseConfier("true")
assert.True(t, bc.DefaultBool(context.Background(), "key1", false)) assert.True(t, bc.DefaultBool("key1", false))
assert.True(t, bc.DefaultBool(context.Background(), "key2", true)) assert.True(t, bc.DefaultBool("key2", true))
} }
func TestBaseConfiger_DefaultFloat(t *testing.T) { func TestBaseConfiger_DefaultFloat(t *testing.T) {
bc := newBaseConfier("12.3") bc := newBaseConfier("12.3")
assert.Equal(t, 12.3, bc.DefaultFloat(context.Background(), "key1", 0.1)) assert.Equal(t, 12.3, bc.DefaultFloat("key1", 0.1))
assert.Equal(t, 0.1, bc.DefaultFloat(context.Background(), "key2", 0.1)) assert.Equal(t, 0.1, bc.DefaultFloat("key2", 0.1))
} }
func TestBaseConfiger_DefaultInt(t *testing.T) { func TestBaseConfiger_DefaultInt(t *testing.T) {
bc := newBaseConfier("10") bc := newBaseConfier("10")
assert.Equal(t, 10, bc.DefaultInt(context.Background(), "key1", 8)) assert.Equal(t, 10, bc.DefaultInt("key1", 8))
assert.Equal(t, 8, bc.DefaultInt(context.Background(), "key2", 8)) assert.Equal(t, 8, bc.DefaultInt("key2", 8))
} }
func TestBaseConfiger_DefaultInt64(t *testing.T) { func TestBaseConfiger_DefaultInt64(t *testing.T) {
bc := newBaseConfier("64") bc := newBaseConfier("64")
assert.Equal(t, int64(64), bc.DefaultInt64(context.Background(), "key1", int64(8))) assert.Equal(t, int64(64), bc.DefaultInt64("key1", int64(8)))
assert.Equal(t, int64(8), bc.DefaultInt64(context.Background(), "key2", int64(8))) assert.Equal(t, int64(8), bc.DefaultInt64("key2", int64(8)))
} }
func TestBaseConfiger_DefaultString(t *testing.T) { func TestBaseConfiger_DefaultString(t *testing.T) {
bc := newBaseConfier("Hello") bc := newBaseConfier("Hello")
assert.Equal(t, "Hello", bc.DefaultString(context.Background(), "key1", "world")) assert.Equal(t, "Hello", bc.DefaultString("key1", "world"))
assert.Equal(t, "world", bc.DefaultString(context.Background(), "key2", "world")) assert.Equal(t, "world", bc.DefaultString("key2", "world"))
} }
func TestBaseConfiger_DefaultStrings(t *testing.T) { func TestBaseConfiger_DefaultStrings(t *testing.T) {
bc := newBaseConfier("Hello;world") bc := newBaseConfier("Hello;world")
assert.Equal(t, []string{"Hello", "world"}, bc.DefaultStrings(context.Background(), "key1", []string{"world"})) assert.Equal(t, []string{"Hello", "world"}, bc.DefaultStrings("key1", []string{"world"}))
assert.Equal(t, []string{"world"}, bc.DefaultStrings(context.Background(), "key2", []string{"world"})) assert.Equal(t, []string{"world"}, bc.DefaultStrings("key2", []string{"world"}))
} }
func newBaseConfier(str1 string) *BaseConfiger { func newBaseConfier(str1 string) *BaseConfiger {

View File

@ -54,34 +54,34 @@ import (
// Configer defines how to get and set value from configuration raw data. // Configer defines how to get and set value from configuration raw data.
type Configer interface { type Configer interface {
// support section::key type in given key when using ini type. // support section::key type in given key when using ini type.
Set(ctx context.Context, key, val string) error Set(key, val string) error
// support section::key type in key string when using ini and json type; Int,Int64,Bool,Float,DIY are same. // support section::key type in key string when using ini and json type; Int,Int64,Bool,Float,DIY are same.
String(ctx context.Context, key string) (string, error) String(key string) (string, error)
// get string slice // get string slice
Strings(ctx context.Context, key string) ([]string, error) Strings(key string) ([]string, error)
Int(ctx context.Context, key string) (int, error) Int(key string) (int, error)
Int64(ctx context.Context, key string) (int64, error) Int64(key string) (int64, error)
Bool(ctx context.Context, key string) (bool, error) Bool(key string) (bool, error)
Float(ctx context.Context, key string) (float64, error) Float(key string) (float64, error)
// support section::key type in key string when using ini and json type; Int,Int64,Bool,Float,DIY are same. // support section::key type in key string when using ini and json type; Int,Int64,Bool,Float,DIY are same.
DefaultString(ctx context.Context, key string, defaultVal string) string DefaultString(key string, defaultVal string) string
// get string slice // get string slice
DefaultStrings(ctx context.Context, key string, defaultVal []string) []string DefaultStrings(key string, defaultVal []string) []string
DefaultInt(ctx context.Context, key string, defaultVal int) int DefaultInt(key string, defaultVal int) int
DefaultInt64(ctx context.Context, key string, defaultVal int64) int64 DefaultInt64(key string, defaultVal int64) int64
DefaultBool(ctx context.Context, key string, defaultVal bool) bool DefaultBool(key string, defaultVal bool) bool
DefaultFloat(ctx context.Context, key string, defaultVal float64) float64 DefaultFloat(key string, defaultVal float64) float64
// DIY return the original value // DIY return the original value
DIY(ctx context.Context, key string) (interface{}, error) DIY(key string) (interface{}, error)
GetSection(ctx context.Context, section string) (map[string]string, error) GetSection(section string) (map[string]string, error)
Unmarshaler(ctx context.Context, prefix string, obj interface{}, opt ...DecodeOption) error Unmarshaler(prefix string, obj interface{}, opt ...DecodeOption) error
Sub(ctx context.Context, key string) (Configer, error) Sub(key string) (Configer, error)
OnChange(ctx context.Context, key string, fn func(value string)) OnChange(key string, fn func(value string))
SaveConfigFile(ctx context.Context, filename string) error SaveConfigFile(filename string) error
} }
type BaseConfiger struct { type BaseConfiger struct {
@ -95,7 +95,7 @@ func NewBaseConfiger(reader func(ctx context.Context, key string) (string, error
} }
} }
func (c *BaseConfiger) Int(ctx context.Context, key string) (int, error) { func (c *BaseConfiger) Int(key string) (int, error) {
res, err := c.reader(context.TODO(), key) res, err := c.reader(context.TODO(), key)
if err != nil { if err != nil {
return 0, err return 0, err
@ -103,7 +103,7 @@ func (c *BaseConfiger) Int(ctx context.Context, key string) (int, error) {
return strconv.Atoi(res) return strconv.Atoi(res)
} }
func (c *BaseConfiger) Int64(ctx context.Context, key string) (int64, error) { func (c *BaseConfiger) Int64(key string) (int64, error) {
res, err := c.reader(context.TODO(), key) res, err := c.reader(context.TODO(), key)
if err != nil { if err != nil {
return 0, err return 0, err
@ -111,7 +111,7 @@ func (c *BaseConfiger) Int64(ctx context.Context, key string) (int64, error) {
return strconv.ParseInt(res, 10, 64) return strconv.ParseInt(res, 10, 64)
} }
func (c *BaseConfiger) Bool(ctx context.Context, key string) (bool, error) { func (c *BaseConfiger) Bool(key string) (bool, error) {
res, err := c.reader(context.TODO(), key) res, err := c.reader(context.TODO(), key)
if err != nil { if err != nil {
return false, err return false, err
@ -119,7 +119,7 @@ func (c *BaseConfiger) Bool(ctx context.Context, key string) (bool, error) {
return ParseBool(res) return ParseBool(res)
} }
func (c *BaseConfiger) Float(ctx context.Context, key string) (float64, error) { func (c *BaseConfiger) Float(key string) (float64, error) {
res, err := c.reader(context.TODO(), key) res, err := c.reader(context.TODO(), key)
if err != nil { if err != nil {
return 0, err return 0, err
@ -129,8 +129,8 @@ func (c *BaseConfiger) Float(ctx context.Context, key string) (float64, error) {
// DefaultString returns the string value for a given key. // DefaultString returns the string value for a given key.
// if err != nil or value is empty return defaultval // if err != nil or value is empty return defaultval
func (c *BaseConfiger) DefaultString(ctx context.Context, key string, defaultVal string) string { func (c *BaseConfiger) DefaultString(key string, defaultVal string) string {
if res, err := c.String(ctx, key); res != "" && err == nil { if res, err := c.String(key); res != "" && err == nil {
return res return res
} }
return defaultVal return defaultVal
@ -138,63 +138,63 @@ func (c *BaseConfiger) DefaultString(ctx context.Context, key string, defaultVal
// DefaultStrings returns the []string value for a given key. // DefaultStrings returns the []string value for a given key.
// if err != nil return defaultval // if err != nil return defaultval
func (c *BaseConfiger) DefaultStrings(ctx context.Context, key string, defaultVal []string) []string { func (c *BaseConfiger) DefaultStrings(key string, defaultVal []string) []string {
if res, err := c.Strings(ctx, key); len(res) > 0 && err == nil { if res, err := c.Strings(key); len(res) > 0 && err == nil {
return res return res
} }
return defaultVal return defaultVal
} }
func (c *BaseConfiger) DefaultInt(ctx context.Context, key string, defaultVal int) int { func (c *BaseConfiger) DefaultInt(key string, defaultVal int) int {
if res, err := c.Int(ctx, key); err == nil { if res, err := c.Int(key); err == nil {
return res return res
} }
return defaultVal return defaultVal
} }
func (c *BaseConfiger) DefaultInt64(ctx context.Context, key string, defaultVal int64) int64 { func (c *BaseConfiger) DefaultInt64(key string, defaultVal int64) int64 {
if res, err := c.Int64(ctx, key); err == nil { if res, err := c.Int64(key); err == nil {
return res return res
} }
return defaultVal return defaultVal
} }
func (c *BaseConfiger) DefaultBool(ctx context.Context, key string, defaultVal bool) bool { func (c *BaseConfiger) DefaultBool(key string, defaultVal bool) bool {
if res, err := c.Bool(ctx, key); err == nil { if res, err := c.Bool(key); err == nil {
return res return res
} }
return defaultVal return defaultVal
} }
func (c *BaseConfiger) DefaultFloat(ctx context.Context, key string, defaultVal float64) float64 { func (c *BaseConfiger) DefaultFloat(key string, defaultVal float64) float64 {
if res, err := c.Float(ctx, key); err == nil { if res, err := c.Float(key); err == nil {
return res return res
} }
return defaultVal return defaultVal
} }
func (c *BaseConfiger) String(ctx context.Context, key string) (string, error) { func (c *BaseConfiger) String(key string) (string, error) {
return c.reader(context.TODO(), key) return c.reader(context.TODO(), key)
} }
// Strings returns the []string value for a given key. // Strings returns the []string value for a given key.
// Return nil if config value does not exist or is empty. // Return nil if config value does not exist or is empty.
func (c *BaseConfiger) Strings(ctx context.Context, key string) ([]string, error) { func (c *BaseConfiger) Strings(key string) ([]string, error) {
res, err := c.String(nil, key) res, err := c.String(key)
if err != nil || res == "" { if err != nil || res == "" {
return nil, err return nil, err
} }
return strings.Split(res, ";"), nil return strings.Split(res, ";"), nil
} }
func (c *BaseConfiger) Unmarshaler(ctx context.Context, prefix string, obj interface{}, opt ...DecodeOption) error { func (c *BaseConfiger) Unmarshaler(prefix string, obj interface{}, opt ...DecodeOption) error {
return errors.New("unsupported operation") return errors.New("unsupported operation")
} }
func (c *BaseConfiger) Sub(ctx context.Context, key string) (Configer, error) { func (c *BaseConfiger) Sub(key string) (Configer, error) {
return nil, errors.New("unsupported operation") return nil, errors.New("unsupported operation")
} }
func (c *BaseConfiger) OnChange(ctx context.Context, key string, fn func(value string)) { func (c *BaseConfiger) OnChange(key string, fn func(value string)) {
// do nothing // do nothing
} }

View File

@ -30,8 +30,6 @@ import (
"github.com/astaxie/beego/core/logs" "github.com/astaxie/beego/core/logs"
) )
const etcdOpts = "etcdOpts"
type EtcdConfiger struct { type EtcdConfiger struct {
prefix string prefix string
client *clientv3.Client client *clientv3.Client
@ -50,7 +48,7 @@ func newEtcdConfiger(client *clientv3.Client, prefix string) *EtcdConfiger {
// reader is an general implementation that read config from etcd. // reader is an general implementation that read config from etcd.
func (e *EtcdConfiger) reader(ctx context.Context, key string) (string, error) { func (e *EtcdConfiger) reader(ctx context.Context, key string) (string, error) {
resp, err := get(e.client, ctx, e.prefix+key) resp, err := get(e.client, e.prefix+key)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -64,29 +62,24 @@ func (e *EtcdConfiger) reader(ctx context.Context, key string) (string, error) {
// Set do nothing and return an error // Set do nothing and return an error
// I think write data to remote config center is not a good practice // I think write data to remote config center is not a good practice
func (e *EtcdConfiger) Set(ctx context.Context, key, val string) error { func (e *EtcdConfiger) Set(key, val string) error {
return errors.New("Unsupported operation") return errors.New("Unsupported operation")
} }
// DIY return the original response from etcd // DIY return the original response from etcd
// be careful when you decide to use this // be careful when you decide to use this
func (e *EtcdConfiger) DIY(ctx context.Context, key string) (interface{}, error) { func (e *EtcdConfiger) DIY(key string) (interface{}, error) {
return get(e.client, context.TODO(), key) return get(e.client, key)
} }
// GetSection in this implementation, we use section as prefix // GetSection in this implementation, we use section as prefix
func (e *EtcdConfiger) GetSection(ctx context.Context, section string) (map[string]string, error) { func (e *EtcdConfiger) GetSection(section string) (map[string]string, error) {
var ( var (
resp *clientv3.GetResponse resp *clientv3.GetResponse
err error err error
) )
if opts, ok := ctx.Value(etcdOpts).([]clientv3.OpOption); ok {
opts = append(opts, clientv3.WithPrefix())
resp, err = e.client.Get(context.TODO(), e.prefix+section, opts...)
} else {
resp, err = e.client.Get(context.TODO(), e.prefix+section, clientv3.WithPrefix()) resp, err = e.client.Get(context.TODO(), e.prefix+section, clientv3.WithPrefix())
}
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "GetSection failed") return nil, errors.WithMessage(err, "GetSection failed")
@ -98,15 +91,15 @@ func (e *EtcdConfiger) GetSection(ctx context.Context, section string) (map[stri
return res, nil return res, nil
} }
func (e *EtcdConfiger) SaveConfigFile(ctx context.Context, filename string) error { func (e *EtcdConfiger) SaveConfigFile(filename string) error {
return errors.New("Unsupported operation") return errors.New("Unsupported operation")
} }
// Unmarshaler is not very powerful because we lost the type information when we get configuration from etcd // Unmarshaler is not very powerful because we lost the type information when we get configuration from etcd
// for example, when we got "5", we are not sure whether it's int 5, or it's string "5" // for example, when we got "5", we are not sure whether it's int 5, or it's string "5"
// TODO(support more complicated decoder) // TODO(support more complicated decoder)
func (e *EtcdConfiger) Unmarshaler(ctx context.Context, prefix string, obj interface{}, opt ...config.DecodeOption) error { func (e *EtcdConfiger) Unmarshaler(prefix string, obj interface{}, opt ...config.DecodeOption) error {
res, err := e.GetSection(ctx, prefix) res, err := e.GetSection(prefix)
if err != nil { if err != nil {
return errors.WithMessage(err, fmt.Sprintf("could not read config with prefix: %s", prefix)) return errors.WithMessage(err, fmt.Sprintf("could not read config with prefix: %s", prefix))
} }
@ -120,22 +113,18 @@ func (e *EtcdConfiger) Unmarshaler(ctx context.Context, prefix string, obj inter
} }
// Sub return an sub configer. // Sub return an sub configer.
func (e *EtcdConfiger) Sub(ctx context.Context, key string) (config.Configer, error) { func (e *EtcdConfiger) Sub(key string) (config.Configer, error) {
return newEtcdConfiger(e.client, e.prefix+key), nil return newEtcdConfiger(e.client, e.prefix+key), nil
} }
// TODO remove this before release v2.0.0 // TODO remove this before release v2.0.0
func (e *EtcdConfiger) OnChange(ctx context.Context, key string, fn func(value string)) { func (e *EtcdConfiger) OnChange(key string, fn func(value string)) {
buildOptsFunc := func() []clientv3.OpOption { buildOptsFunc := func() []clientv3.OpOption {
if opts, ok := ctx.Value(etcdOpts).([]clientv3.OpOption); ok {
opts = append(opts, clientv3.WithCreatedNotify())
return opts
}
return []clientv3.OpOption{} return []clientv3.OpOption{}
} }
rch := e.client.Watch(ctx, e.prefix+key, buildOptsFunc()...) rch := e.client.Watch(context.Background(), e.prefix+key, buildOptsFunc()...)
go func() { go func() {
for { for {
for resp := range rch { for resp := range rch {
@ -152,7 +141,7 @@ func (e *EtcdConfiger) OnChange(ctx context.Context, key string, fn func(value s
} }
} }
time.Sleep(time.Second) time.Sleep(time.Second)
rch = e.client.Watch(ctx, e.prefix+key, buildOptsFunc()...) rch = e.client.Watch(context.Background(), e.prefix+key, buildOptsFunc()...)
} }
}() }()
@ -188,16 +177,12 @@ func (provider *EtcdConfigerProvider) ParseData(data []byte) (config.Configer, e
return newEtcdConfiger(client, ""), nil return newEtcdConfiger(client, ""), nil
} }
func get(client *clientv3.Client, ctx context.Context, key string) (*clientv3.GetResponse, error) { func get(client *clientv3.Client, key string) (*clientv3.GetResponse, error) {
var ( var (
resp *clientv3.GetResponse resp *clientv3.GetResponse
err error err error
) )
if opts, ok := ctx.Value(etcdOpts).([]clientv3.OpOption); ok { resp, err = client.Get(context.Background(), key)
resp, err = client.Get(ctx, key, opts...)
} else {
resp, err = client.Get(ctx, key)
}
if err != nil { if err != nil {
return nil, errors.WithMessage(err, fmt.Sprintf("read config from etcd with key %s failed", key)) return nil, errors.WithMessage(err, fmt.Sprintf("read config from etcd with key %s failed", key))
@ -205,10 +190,6 @@ func get(client *clientv3.Client, ctx context.Context, key string) (*clientv3.Ge
return resp, err return resp, err
} }
func WithEtcdOption(ctx context.Context, opts ...clientv3.OpOption) context.Context {
return context.WithValue(ctx, etcdOpts, opts)
}
func init() { func init() {
config.Register("json", &EtcdConfigerProvider{}) config.Register("json", &EtcdConfigerProvider{})
} }

View File

@ -15,7 +15,6 @@
package etcd package etcd
import ( import (
"context"
"encoding/json" "encoding/json"
"os" "os"
"testing" "testing"
@ -25,11 +24,6 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestWithEtcdOption(t *testing.T) {
ctx := WithEtcdOption(context.Background(), clientv3.WithPrefix())
assert.NotNil(t, ctx.Value(etcdOpts))
}
func TestEtcdConfigerProvider_Parse(t *testing.T) { func TestEtcdConfigerProvider_Parse(t *testing.T) {
provider := &EtcdConfigerProvider{} provider := &EtcdConfigerProvider{}
cfger, err := provider.Parse(readEtcdConfig()) cfger, err := provider.Parse(readEtcdConfig())
@ -42,59 +36,59 @@ func TestEtcdConfiger(t *testing.T) {
provider := &EtcdConfigerProvider{} provider := &EtcdConfigerProvider{}
cfger, _ := provider.Parse(readEtcdConfig()) cfger, _ := provider.Parse(readEtcdConfig())
subCfger, err := cfger.Sub(nil, "sub.") subCfger, err := cfger.Sub("sub.")
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, subCfger) assert.NotNil(t, subCfger)
subSubCfger, err := subCfger.Sub(nil, "sub.") subSubCfger, err := subCfger.Sub("sub.")
assert.NotNil(t, subSubCfger) assert.NotNil(t, subSubCfger)
assert.Nil(t, err) assert.Nil(t, err)
str, err := subSubCfger.String(nil, "key1") str, err := subSubCfger.String("key1")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "sub.sub.key", str) assert.Equal(t, "sub.sub.key", str)
// we cannot test it // we cannot test it
subSubCfger.OnChange(context.Background(), "watch", func(value string) { subSubCfger.OnChange("watch", func(value string) {
// do nothing // do nothing
}) })
defStr := cfger.DefaultString(nil, "not_exit", "default value") defStr := cfger.DefaultString("not_exit", "default value")
assert.Equal(t, "default value", defStr) assert.Equal(t, "default value", defStr)
defInt64 := cfger.DefaultInt64(nil, "not_exit", -1) defInt64 := cfger.DefaultInt64("not_exit", -1)
assert.Equal(t, int64(-1), defInt64) assert.Equal(t, int64(-1), defInt64)
defInt := cfger.DefaultInt(nil, "not_exit", -2) defInt := cfger.DefaultInt("not_exit", -2)
assert.Equal(t, -2, defInt) assert.Equal(t, -2, defInt)
defFlt := cfger.DefaultFloat(nil, "not_exit", 12.3) defFlt := cfger.DefaultFloat("not_exit", 12.3)
assert.Equal(t, 12.3, defFlt) assert.Equal(t, 12.3, defFlt)
defBl := cfger.DefaultBool(nil, "not_exit", true) defBl := cfger.DefaultBool("not_exit", true)
assert.True(t, defBl) assert.True(t, defBl)
defStrs := cfger.DefaultStrings(nil, "not_exit", []string{"hello"}) defStrs := cfger.DefaultStrings("not_exit", []string{"hello"})
assert.Equal(t, []string{"hello"}, defStrs) assert.Equal(t, []string{"hello"}, defStrs)
fl, err := cfger.Float(nil, "current.float") fl, err := cfger.Float("current.float")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, 1.23, fl) assert.Equal(t, 1.23, fl)
bl, err := cfger.Bool(nil, "current.bool") bl, err := cfger.Bool("current.bool")
assert.Nil(t, err) assert.Nil(t, err)
assert.True(t, bl) assert.True(t, bl)
it, err := cfger.Int(nil, "current.int") it, err := cfger.Int("current.int")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, 11, it) assert.Equal(t, 11, it)
str, err = cfger.String(nil, "current.string") str, err = cfger.String("current.string")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "hello", str) assert.Equal(t, "hello", str)
tn := &TestEntity{} tn := &TestEntity{}
err = cfger.Unmarshaler(context.Background(), "current.serialize.", tn) err = cfger.Unmarshaler("current.serialize.", tn)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "test", tn.Name) assert.Equal(t, "test", tn.Name)
} }

View File

@ -30,71 +30,71 @@ func (c *fakeConfigContainer) getData(key string) string {
return c.data[strings.ToLower(key)] return c.data[strings.ToLower(key)]
} }
func (c *fakeConfigContainer) Set(ctx context.Context, key, val string) error { func (c *fakeConfigContainer) Set(key, val string) error {
c.data[strings.ToLower(key)] = val c.data[strings.ToLower(key)] = val
return nil return nil
} }
func (c *fakeConfigContainer) Int(ctx context.Context, key string) (int, error) { func (c *fakeConfigContainer) Int(key string) (int, error) {
return strconv.Atoi(c.getData(key)) return strconv.Atoi(c.getData(key))
} }
func (c *fakeConfigContainer) DefaultInt(ctx context.Context, key string, defaultVal int) int { func (c *fakeConfigContainer) DefaultInt(key string, defaultVal int) int {
v, err := c.Int(ctx, key) v, err := c.Int(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
} }
return v return v
} }
func (c *fakeConfigContainer) Int64(ctx context.Context, key string) (int64, error) { func (c *fakeConfigContainer) Int64(key string) (int64, error) {
return strconv.ParseInt(c.getData(key), 10, 64) return strconv.ParseInt(c.getData(key), 10, 64)
} }
func (c *fakeConfigContainer) DefaultInt64(ctx context.Context, key string, defaultVal int64) int64 { func (c *fakeConfigContainer) DefaultInt64(key string, defaultVal int64) int64 {
v, err := c.Int64(ctx, key) v, err := c.Int64(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
} }
return v return v
} }
func (c *fakeConfigContainer) Bool(ctx context.Context, key string) (bool, error) { func (c *fakeConfigContainer) Bool(key string) (bool, error) {
return ParseBool(c.getData(key)) return ParseBool(c.getData(key))
} }
func (c *fakeConfigContainer) DefaultBool(ctx context.Context, key string, defaultVal bool) bool { func (c *fakeConfigContainer) DefaultBool(key string, defaultVal bool) bool {
v, err := c.Bool(ctx, key) v, err := c.Bool(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
} }
return v return v
} }
func (c *fakeConfigContainer) Float(ctx context.Context, key string) (float64, error) { func (c *fakeConfigContainer) Float(key string) (float64, error) {
return strconv.ParseFloat(c.getData(key), 64) return strconv.ParseFloat(c.getData(key), 64)
} }
func (c *fakeConfigContainer) DefaultFloat(ctx context.Context, key string, defaultVal float64) float64 { func (c *fakeConfigContainer) DefaultFloat(key string, defaultVal float64) float64 {
v, err := c.Float(ctx, key) v, err := c.Float(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
} }
return v return v
} }
func (c *fakeConfigContainer) DIY(ctx context.Context, key string) (interface{}, error) { func (c *fakeConfigContainer) DIY(key string) (interface{}, error) {
if v, ok := c.data[strings.ToLower(key)]; ok { if v, ok := c.data[strings.ToLower(key)]; ok {
return v, nil return v, nil
} }
return nil, errors.New("key not find") return nil, errors.New("key not find")
} }
func (c *fakeConfigContainer) GetSection(ctx context.Context, section string) (map[string]string, error) { func (c *fakeConfigContainer) GetSection(section string) (map[string]string, error) {
return nil, errors.New("not implement in the fakeConfigContainer") return nil, errors.New("not implement in the fakeConfigContainer")
} }
func (c *fakeConfigContainer) SaveConfigFile(ctx context.Context, filename string) error { func (c *fakeConfigContainer) SaveConfigFile(filename string) error {
return errors.New("not implement in the fakeConfigContainer") return errors.New("not implement in the fakeConfigContainer")
} }

View File

@ -238,14 +238,14 @@ type IniConfigContainer struct {
} }
// Bool returns the boolean value for a given key. // Bool returns the boolean value for a given key.
func (c *IniConfigContainer) Bool(ctx context.Context, key string) (bool, error) { func (c *IniConfigContainer) Bool(key string) (bool, error) {
return ParseBool(c.getdata(key)) return ParseBool(c.getdata(key))
} }
// DefaultBool returns the boolean value for a given key. // DefaultBool returns the boolean value for a given key.
// if err != nil return defaultVal // if err != nil return defaultVal
func (c *IniConfigContainer) DefaultBool(ctx context.Context, key string, defaultVal bool) bool { func (c *IniConfigContainer) DefaultBool(key string, defaultVal bool) bool {
v, err := c.Bool(ctx, key) v, err := c.Bool(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
} }
@ -253,14 +253,14 @@ func (c *IniConfigContainer) DefaultBool(ctx context.Context, key string, defaul
} }
// Int returns the integer value for a given key. // Int returns the integer value for a given key.
func (c *IniConfigContainer) Int(ctx context.Context, key string) (int, error) { func (c *IniConfigContainer) Int(key string) (int, error) {
return strconv.Atoi(c.getdata(key)) return strconv.Atoi(c.getdata(key))
} }
// DefaultInt returns the integer value for a given key. // DefaultInt returns the integer value for a given key.
// if err != nil return defaultVal // if err != nil return defaultVal
func (c *IniConfigContainer) DefaultInt(ctx context.Context, key string, defaultVal int) int { func (c *IniConfigContainer) DefaultInt(key string, defaultVal int) int {
v, err := c.Int(ctx, key) v, err := c.Int(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
} }
@ -268,14 +268,14 @@ func (c *IniConfigContainer) DefaultInt(ctx context.Context, key string, default
} }
// Int64 returns the int64 value for a given key. // Int64 returns the int64 value for a given key.
func (c *IniConfigContainer) Int64(ctx context.Context, key string) (int64, error) { func (c *IniConfigContainer) Int64(key string) (int64, error) {
return strconv.ParseInt(c.getdata(key), 10, 64) return strconv.ParseInt(c.getdata(key), 10, 64)
} }
// DefaultInt64 returns the int64 value for a given key. // DefaultInt64 returns the int64 value for a given key.
// if err != nil return defaultVal // if err != nil return defaultVal
func (c *IniConfigContainer) DefaultInt64(ctx context.Context, key string, defaultVal int64) int64 { func (c *IniConfigContainer) DefaultInt64(key string, defaultVal int64) int64 {
v, err := c.Int64(ctx, key) v, err := c.Int64(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
} }
@ -283,14 +283,14 @@ func (c *IniConfigContainer) DefaultInt64(ctx context.Context, key string, defau
} }
// Float returns the float value for a given key. // Float returns the float value for a given key.
func (c *IniConfigContainer) Float(ctx context.Context, key string) (float64, error) { func (c *IniConfigContainer) Float(key string) (float64, error) {
return strconv.ParseFloat(c.getdata(key), 64) return strconv.ParseFloat(c.getdata(key), 64)
} }
// DefaultFloat returns the float64 value for a given key. // DefaultFloat returns the float64 value for a given key.
// if err != nil return defaultVal // if err != nil return defaultVal
func (c *IniConfigContainer) DefaultFloat(ctx context.Context, key string, defaultVal float64) float64 { func (c *IniConfigContainer) DefaultFloat(key string, defaultVal float64) float64 {
v, err := c.Float(ctx, key) v, err := c.Float(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
} }
@ -298,14 +298,14 @@ func (c *IniConfigContainer) DefaultFloat(ctx context.Context, key string, defau
} }
// String returns the string value for a given key. // String returns the string value for a given key.
func (c *IniConfigContainer) String(ctx context.Context, key string) (string, error) { func (c *IniConfigContainer) String(key string) (string, error) {
return c.getdata(key), nil return c.getdata(key), nil
} }
// DefaultString returns the string value for a given key. // DefaultString returns the string value for a given key.
// if err != nil return defaultVal // if err != nil return defaultVal
func (c *IniConfigContainer) DefaultString(ctx context.Context, key string, defaultVal string) string { func (c *IniConfigContainer) DefaultString(key string, defaultVal string) string {
v, err := c.String(nil, key) v, err := c.String(key)
if v == "" || err != nil { if v == "" || err != nil {
return defaultVal return defaultVal
} }
@ -314,8 +314,8 @@ func (c *IniConfigContainer) DefaultString(ctx context.Context, key string, defa
// Strings returns the []string value for a given key. // Strings returns the []string value for a given key.
// Return nil if config value does not exist or is empty. // Return nil if config value does not exist or is empty.
func (c *IniConfigContainer) Strings(ctx context.Context, key string) ([]string, error) { func (c *IniConfigContainer) Strings(key string) ([]string, error) {
v, err := c.String(nil, key) v, err := c.String(key)
if v == "" || err != nil { if v == "" || err != nil {
return nil, err return nil, err
} }
@ -324,8 +324,8 @@ func (c *IniConfigContainer) Strings(ctx context.Context, key string) ([]string,
// DefaultStrings returns the []string value for a given key. // DefaultStrings returns the []string value for a given key.
// if err != nil return defaultVal // if err != nil return defaultVal
func (c *IniConfigContainer) DefaultStrings(ctx context.Context, key string, defaultVal []string) []string { func (c *IniConfigContainer) DefaultStrings(key string, defaultVal []string) []string {
v, err := c.Strings(ctx, key) v, err := c.Strings(key)
if v == nil || err != nil { if v == nil || err != nil {
return defaultVal return defaultVal
} }
@ -333,7 +333,7 @@ func (c *IniConfigContainer) DefaultStrings(ctx context.Context, key string, def
} }
// GetSection returns map for the given section // GetSection returns map for the given section
func (c *IniConfigContainer) GetSection(ctx context.Context, section string) (map[string]string, error) { func (c *IniConfigContainer) GetSection(section string) (map[string]string, error) {
if v, ok := c.data[section]; ok { if v, ok := c.data[section]; ok {
return v, nil return v, nil
} }
@ -343,7 +343,7 @@ func (c *IniConfigContainer) GetSection(ctx context.Context, section string) (ma
// SaveConfigFile save the config into file. // SaveConfigFile save the config into file.
// //
// BUG(env): The environment variable config item will be saved with real value in SaveConfigFile Function. // BUG(env): The environment variable config item will be saved with real value in SaveConfigFile Function.
func (c *IniConfigContainer) SaveConfigFile(ctx context.Context, filename string) (err error) { func (c *IniConfigContainer) SaveConfigFile(filename string) (err error) {
// Write configuration file by filename. // Write configuration file by filename.
f, err := os.Create(filename) f, err := os.Create(filename)
if err != nil { if err != nil {
@ -443,7 +443,7 @@ func (c *IniConfigContainer) SaveConfigFile(ctx context.Context, filename string
// Set writes a new value for key. // Set writes a new value for key.
// if write to one section, the key need be "section::key". // if write to one section, the key need be "section::key".
// if the section is not existed, it panics. // if the section is not existed, it panics.
func (c *IniConfigContainer) Set(ctx context.Context, key, val string) error { func (c *IniConfigContainer) Set(key, val string) error {
c.Lock() c.Lock()
defer c.Unlock() defer c.Unlock()
if len(key) == 0 { if len(key) == 0 {
@ -471,7 +471,7 @@ func (c *IniConfigContainer) Set(ctx context.Context, key, val string) error {
} }
// DIY returns the raw value by a given key. // DIY returns the raw value by a given key.
func (c *IniConfigContainer) DIY(ctx context.Context, key string) (v interface{}, err error) { func (c *IniConfigContainer) DIY(key string) (v interface{}, err error) {
if v, ok := c.data[strings.ToLower(key)]; ok { if v, ok := c.data[strings.ToLower(key)]; ok {
return v, nil return v, nil
} }

View File

@ -101,19 +101,19 @@ password = ${GOPATH}
var value interface{} var value interface{}
switch v.(type) { switch v.(type) {
case int: case int:
value, err = iniconf.Int(nil, k) value, err = iniconf.Int(k)
case int64: case int64:
value, err = iniconf.Int64(nil, k) value, err = iniconf.Int64(k)
case float64: case float64:
value, err = iniconf.Float(nil, k) value, err = iniconf.Float(k)
case bool: case bool:
value, err = iniconf.Bool(nil, k) value, err = iniconf.Bool(k)
case []string: case []string:
value, err = iniconf.Strings(nil, k) value, err = iniconf.Strings(k)
case string: case string:
value, err = iniconf.String(nil, k) value, err = iniconf.String(k)
default: default:
value, err = iniconf.DIY(nil, k) value, err = iniconf.DIY(k)
} }
if err != nil { if err != nil {
t.Fatalf("get key %q value fail,err %s", k, err) t.Fatalf("get key %q value fail,err %s", k, err)
@ -122,10 +122,10 @@ password = ${GOPATH}
} }
} }
if err = iniconf.Set(nil, "name", "astaxie"); err != nil { if err = iniconf.Set("name", "astaxie"); err != nil {
t.Fatal(err) t.Fatal(err)
} }
res, _ := iniconf.String(nil, "name") res, _ := iniconf.String("name")
if res != "astaxie" { if res != "astaxie" {
t.Fatal("get name error") t.Fatal("get name error")
} }
@ -171,7 +171,7 @@ name=mysql
t.Fatal(err) t.Fatal(err)
} }
name := "newIniConfig.ini" name := "newIniConfig.ini"
if err := cfg.SaveConfigFile(nil, name); err != nil { if err := cfg.SaveConfigFile(name); err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer os.Remove(name) defer os.Remove(name)

View File

@ -15,7 +15,6 @@
package json package json
import ( import (
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@ -77,16 +76,16 @@ type JSONConfigContainer struct {
sync.RWMutex sync.RWMutex
} }
func (c *JSONConfigContainer) Unmarshaler(ctx context.Context, prefix string, obj interface{}, opt ...config.DecodeOption) error { func (c *JSONConfigContainer) Unmarshaler(prefix string, obj interface{}, opt ...config.DecodeOption) error {
sub, err := c.sub(ctx, prefix) sub, err := c.sub(prefix)
if err != nil { if err != nil {
return err return err
} }
return mapstructure.Decode(sub, obj) return mapstructure.Decode(sub, obj)
} }
func (c *JSONConfigContainer) Sub(ctx context.Context, key string) (config.Configer, error) { func (c *JSONConfigContainer) Sub(key string) (config.Configer, error) {
sub, err := c.sub(ctx, key) sub, err := c.sub(key)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -95,7 +94,7 @@ func (c *JSONConfigContainer) Sub(ctx context.Context, key string) (config.Confi
}, nil }, nil
} }
func (c *JSONConfigContainer) sub(ctx context.Context, key string) (map[string]interface{}, error) { func (c *JSONConfigContainer) sub(key string) (map[string]interface{}, error) {
if key == "" { if key == "" {
return c.data, nil return c.data, nil
} }
@ -111,12 +110,12 @@ func (c *JSONConfigContainer) sub(ctx context.Context, key string) (map[string]i
return res, nil return res, nil
} }
func (c *JSONConfigContainer) OnChange(ctx context.Context, key string, fn func(value string)) { func (c *JSONConfigContainer) OnChange(key string, fn func(value string)) {
logs.Warn("unsupported operation") logs.Warn("unsupported operation")
} }
// Bool returns the boolean value for a given key. // Bool returns the boolean value for a given key.
func (c *JSONConfigContainer) Bool(ctx context.Context, key string) (bool, error) { func (c *JSONConfigContainer) Bool(key string) (bool, error) {
val := c.getData(key) val := c.getData(key)
if val != nil { if val != nil {
return config.ParseBool(val) return config.ParseBool(val)
@ -126,15 +125,15 @@ func (c *JSONConfigContainer) Bool(ctx context.Context, key string) (bool, error
// DefaultBool return the bool value if has no error // DefaultBool return the bool value if has no error
// otherwise return the defaultval // otherwise return the defaultval
func (c *JSONConfigContainer) DefaultBool(ctx context.Context, key string, defaultVal bool) bool { func (c *JSONConfigContainer) DefaultBool(key string, defaultVal bool) bool {
if v, err := c.Bool(ctx, key); err == nil { if v, err := c.Bool(key); err == nil {
return v return v
} }
return defaultVal return defaultVal
} }
// Int returns the integer value for a given key. // Int returns the integer value for a given key.
func (c *JSONConfigContainer) Int(ctx context.Context, key string) (int, error) { func (c *JSONConfigContainer) Int(key string) (int, error) {
val := c.getData(key) val := c.getData(key)
if val != nil { if val != nil {
if v, ok := val.(float64); ok { if v, ok := val.(float64); ok {
@ -149,15 +148,15 @@ func (c *JSONConfigContainer) Int(ctx context.Context, key string) (int, error)
// DefaultInt returns the integer value for a given key. // DefaultInt returns the integer value for a given key.
// if err != nil return defaultval // if err != nil return defaultval
func (c *JSONConfigContainer) DefaultInt(ctx context.Context, key string, defaultVal int) int { func (c *JSONConfigContainer) DefaultInt(key string, defaultVal int) int {
if v, err := c.Int(ctx, key); err == nil { if v, err := c.Int(key); err == nil {
return v return v
} }
return defaultVal return defaultVal
} }
// Int64 returns the int64 value for a given key. // Int64 returns the int64 value for a given key.
func (c *JSONConfigContainer) Int64(ctx context.Context, key string) (int64, error) { func (c *JSONConfigContainer) Int64(key string) (int64, error) {
val := c.getData(key) val := c.getData(key)
if val != nil { if val != nil {
if v, ok := val.(float64); ok { if v, ok := val.(float64); ok {
@ -170,15 +169,15 @@ func (c *JSONConfigContainer) Int64(ctx context.Context, key string) (int64, err
// DefaultInt64 returns the int64 value for a given key. // DefaultInt64 returns the int64 value for a given key.
// if err != nil return defaultval // if err != nil return defaultval
func (c *JSONConfigContainer) DefaultInt64(ctx context.Context, key string, defaultVal int64) int64 { func (c *JSONConfigContainer) DefaultInt64(key string, defaultVal int64) int64 {
if v, err := c.Int64(ctx, key); err == nil { if v, err := c.Int64(key); err == nil {
return v return v
} }
return defaultVal return defaultVal
} }
// Float returns the float value for a given key. // Float returns the float value for a given key.
func (c *JSONConfigContainer) Float(ctx context.Context, key string) (float64, error) { func (c *JSONConfigContainer) Float(key string) (float64, error) {
val := c.getData(key) val := c.getData(key)
if val != nil { if val != nil {
if v, ok := val.(float64); ok { if v, ok := val.(float64); ok {
@ -191,15 +190,15 @@ func (c *JSONConfigContainer) Float(ctx context.Context, key string) (float64, e
// DefaultFloat returns the float64 value for a given key. // DefaultFloat returns the float64 value for a given key.
// if err != nil return defaultval // if err != nil return defaultval
func (c *JSONConfigContainer) DefaultFloat(ctx context.Context, key string, defaultVal float64) float64 { func (c *JSONConfigContainer) DefaultFloat(key string, defaultVal float64) float64 {
if v, err := c.Float(ctx, key); err == nil { if v, err := c.Float(key); err == nil {
return v return v
} }
return defaultVal return defaultVal
} }
// String returns the string value for a given key. // String returns the string value for a given key.
func (c *JSONConfigContainer) String(ctx context.Context, key string) (string, error) { func (c *JSONConfigContainer) String(key string) (string, error) {
val := c.getData(key) val := c.getData(key)
if val != nil { if val != nil {
if v, ok := val.(string); ok { if v, ok := val.(string); ok {
@ -211,17 +210,17 @@ func (c *JSONConfigContainer) String(ctx context.Context, key string) (string, e
// DefaultString returns the string value for a given key. // DefaultString returns the string value for a given key.
// if err != nil return defaultval // if err != nil return defaultval
func (c *JSONConfigContainer) DefaultString(ctx context.Context, key string, defaultVal string) string { func (c *JSONConfigContainer) DefaultString(key string, defaultVal string) string {
// TODO FIXME should not use "" to replace non existence // TODO FIXME should not use "" to replace non existence
if v, err := c.String(ctx, key); v != "" && err == nil { if v, err := c.String(key); v != "" && err == nil {
return v return v
} }
return defaultVal return defaultVal
} }
// Strings returns the []string value for a given key. // Strings returns the []string value for a given key.
func (c *JSONConfigContainer) Strings(ctx context.Context, key string) ([]string, error) { func (c *JSONConfigContainer) Strings(key string) ([]string, error) {
stringVal, err := c.String(nil, key) stringVal, err := c.String(key)
if stringVal == "" || err != nil { if stringVal == "" || err != nil {
return nil, err return nil, err
} }
@ -230,15 +229,15 @@ func (c *JSONConfigContainer) Strings(ctx context.Context, key string) ([]string
// DefaultStrings returns the []string value for a given key. // DefaultStrings returns the []string value for a given key.
// if err != nil return defaultval // if err != nil return defaultval
func (c *JSONConfigContainer) DefaultStrings(ctx context.Context, key string, defaultVal []string) []string { func (c *JSONConfigContainer) DefaultStrings(key string, defaultVal []string) []string {
if v, err := c.Strings(ctx, key); v != nil && err == nil { if v, err := c.Strings(key); v != nil && err == nil {
return v return v
} }
return defaultVal return defaultVal
} }
// GetSection returns map for the given section // GetSection returns map for the given section
func (c *JSONConfigContainer) GetSection(ctx context.Context, section string) (map[string]string, error) { func (c *JSONConfigContainer) GetSection(section string) (map[string]string, error) {
if v, ok := c.data[section]; ok { if v, ok := c.data[section]; ok {
return v.(map[string]string), nil return v.(map[string]string), nil
} }
@ -246,7 +245,7 @@ func (c *JSONConfigContainer) GetSection(ctx context.Context, section string) (m
} }
// SaveConfigFile save the config into file // SaveConfigFile save the config into file
func (c *JSONConfigContainer) SaveConfigFile(ctx context.Context, filename string) (err error) { func (c *JSONConfigContainer) SaveConfigFile(filename string) (err error) {
// Write configuration file by filename. // Write configuration file by filename.
f, err := os.Create(filename) f, err := os.Create(filename)
if err != nil { if err != nil {
@ -262,7 +261,7 @@ func (c *JSONConfigContainer) SaveConfigFile(ctx context.Context, filename strin
} }
// Set writes a new value for key. // Set writes a new value for key.
func (c *JSONConfigContainer) Set(ctx context.Context, key, val string) error { func (c *JSONConfigContainer) Set(key, val string) error {
c.Lock() c.Lock()
defer c.Unlock() defer c.Unlock()
c.data[key] = val c.data[key] = val
@ -270,7 +269,7 @@ func (c *JSONConfigContainer) Set(ctx context.Context, key, val string) error {
} }
// DIY returns the raw value by a given key. // DIY returns the raw value by a given key.
func (c *JSONConfigContainer) DIY(ctx context.Context, key string) (v interface{}, err error) { func (c *JSONConfigContainer) DIY(key string) (v interface{}, err error) {
val := c.getData(key) val := c.getData(key)
if val != nil { if val != nil {
return val, nil return val, nil

View File

@ -15,7 +15,6 @@
package json package json
import ( import (
"context"
"fmt" "fmt"
"os" "os"
"testing" "testing"
@ -52,7 +51,7 @@ func TestJsonStartsWithArray(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
rootArray, err := jsonconf.DIY(nil, "rootArray") rootArray, err := jsonconf.DIY("rootArray")
if err != nil { if err != nil {
t.Error("array does not exist as element") t.Error("array does not exist as element")
} }
@ -158,19 +157,19 @@ func TestJson(t *testing.T) {
var value interface{} var value interface{}
switch v.(type) { switch v.(type) {
case int: case int:
value, err = jsonconf.Int(nil, k) value, err = jsonconf.Int(k)
case int64: case int64:
value, err = jsonconf.Int64(nil, k) value, err = jsonconf.Int64(k)
case float64: case float64:
value, err = jsonconf.Float(nil, k) value, err = jsonconf.Float(k)
case bool: case bool:
value, err = jsonconf.Bool(nil, k) value, err = jsonconf.Bool(k)
case []string: case []string:
value, err = jsonconf.Strings(nil, k) value, err = jsonconf.Strings(k)
case string: case string:
value, err = jsonconf.String(nil, k) value, err = jsonconf.String(k)
default: default:
value, err = jsonconf.DIY(nil, k) value, err = jsonconf.DIY(k)
} }
if err != nil { if err != nil {
t.Fatalf("get key %q value fatal,%v err %s", k, v, err) t.Fatalf("get key %q value fatal,%v err %s", k, v, err)
@ -179,16 +178,16 @@ func TestJson(t *testing.T) {
} }
} }
if err = jsonconf.Set(nil, "name", "astaxie"); err != nil { if err = jsonconf.Set("name", "astaxie"); err != nil {
t.Fatal(err) t.Fatal(err)
} }
res, _ := jsonconf.String(nil, "name") res, _ := jsonconf.String("name")
if res != "astaxie" { if res != "astaxie" {
t.Fatal("get name error") t.Fatal("get name error")
} }
if db, err := jsonconf.DIY(nil, "database"); err != nil { if db, err := jsonconf.DIY("database"); err != nil {
t.Fatal(err) t.Fatal(err)
} else if m, ok := db.(map[string]interface{}); !ok { } else if m, ok := db.(map[string]interface{}); !ok {
t.Log(db) t.Log(db)
@ -199,46 +198,46 @@ func TestJson(t *testing.T) {
} }
} }
if _, err := jsonconf.Int(nil, "unknown"); err == nil { if _, err := jsonconf.Int("unknown"); err == nil {
t.Error("unknown keys should return an error when expecting an Int") t.Error("unknown keys should return an error when expecting an Int")
} }
if _, err := jsonconf.Int64(nil, "unknown"); err == nil { if _, err := jsonconf.Int64("unknown"); err == nil {
t.Error("unknown keys should return an error when expecting an Int64") t.Error("unknown keys should return an error when expecting an Int64")
} }
if _, err := jsonconf.Float(nil, "unknown"); err == nil { if _, err := jsonconf.Float("unknown"); err == nil {
t.Error("unknown keys should return an error when expecting a Float") t.Error("unknown keys should return an error when expecting a Float")
} }
if _, err := jsonconf.DIY(nil, "unknown"); err == nil { if _, err := jsonconf.DIY("unknown"); err == nil {
t.Error("unknown keys should return an error when expecting an interface{}") t.Error("unknown keys should return an error when expecting an interface{}")
} }
if val, _ := jsonconf.String(nil, "unknown"); val != "" { if val, _ := jsonconf.String("unknown"); val != "" {
t.Error("unknown keys should return an empty string when expecting a String") t.Error("unknown keys should return an empty string when expecting a String")
} }
if _, err := jsonconf.Bool(nil, "unknown"); err == nil { if _, err := jsonconf.Bool("unknown"); err == nil {
t.Error("unknown keys should return an error when expecting a Bool") t.Error("unknown keys should return an error when expecting a Bool")
} }
if !jsonconf.DefaultBool(nil, "unknown", true) { if !jsonconf.DefaultBool("unknown", true) {
t.Error("unknown keys with default value wrong") t.Error("unknown keys with default value wrong")
} }
sub, err := jsonconf.Sub(context.Background(), "database") sub, err := jsonconf.Sub("database")
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, sub) assert.NotNil(t, sub)
sub, err = sub.Sub(context.Background(), "conns") sub, err = sub.Sub("conns")
assert.Nil(t, err) assert.Nil(t, err)
maxCon, _ := sub.Int(context.Background(), "maxconnection") maxCon, _ := sub.Int("maxconnection")
assert.Equal(t, 12, maxCon) assert.Equal(t, 12, maxCon)
dbCfg := &DatabaseConfig{} dbCfg := &DatabaseConfig{}
err = sub.Unmarshaler(context.Background(), "", dbCfg) err = sub.Unmarshaler("", dbCfg)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, 12, dbCfg.MaxConnection) assert.Equal(t, 12, dbCfg.MaxConnection)
assert.True(t, dbCfg.Autoconnect) assert.True(t, dbCfg.Autoconnect)

View File

@ -15,7 +15,6 @@
package toml package toml
import ( import (
"context"
"io/ioutil" "io/ioutil"
"os" "os"
"strings" "strings"
@ -57,7 +56,7 @@ type configContainer struct {
} }
// Set put key, val // Set put key, val
func (c *configContainer) Set(ctx context.Context, key, val string) error { func (c *configContainer) Set(key, val string) error {
path := strings.Split(key, keySeparator) path := strings.Split(key, keySeparator)
sub, err := subTree(c.t, path[0:len(path)-1]) sub, err := subTree(c.t, path[0:len(path)-1])
if err != nil { if err != nil {
@ -69,7 +68,7 @@ func (c *configContainer) Set(ctx context.Context, key, val string) error {
// String return the value. // String return the value.
// return error if key not found or value is invalid type // return error if key not found or value is invalid type
func (c *configContainer) String(ctx context.Context, key string) (string, error) { func (c *configContainer) String(key string) (string, error) {
res, err := c.get(key) res, err := c.get(key)
if err != nil { if err != nil {
@ -89,7 +88,7 @@ func (c *configContainer) String(ctx context.Context, key string) (string, error
// Strings return []string // Strings return []string
// return error if key not found or value is invalid type // return error if key not found or value is invalid type
func (c *configContainer) Strings(ctx context.Context, key string) ([]string, error) { func (c *configContainer) Strings(key string) ([]string, error) {
val, err := c.get(key) val, err := c.get(key)
if err != nil { if err != nil {
@ -115,14 +114,14 @@ func (c *configContainer) Strings(ctx context.Context, key string) ([]string, er
// Int return int value // Int return int value
// return error if key not found or value is invalid type // return error if key not found or value is invalid type
func (c *configContainer) Int(ctx context.Context, key string) (int, error) { func (c *configContainer) Int(key string) (int, error) {
val, err := c.Int64(ctx, key) val, err := c.Int64(key)
return int(val), err return int(val), err
} }
// Int64 return int64 value // Int64 return int64 value
// return error if key not found or value is invalid type // return error if key not found or value is invalid type
func (c *configContainer) Int64(ctx context.Context, key string) (int64, error) { func (c *configContainer) Int64(key string) (int64, error) {
res, err := c.get(key) res, err := c.get(key)
if err != nil { if err != nil {
return 0, err return 0, err
@ -141,7 +140,7 @@ func (c *configContainer) Int64(ctx context.Context, key string) (int64, error)
// bool return bool value // bool return bool value
// return error if key not found or value is invalid type // return error if key not found or value is invalid type
func (c *configContainer) Bool(ctx context.Context, key string) (bool, error) { func (c *configContainer) Bool(key string) (bool, error) {
res, err := c.get(key) res, err := c.get(key)
@ -161,7 +160,7 @@ func (c *configContainer) Bool(ctx context.Context, key string) (bool, error) {
// Float return float value // Float return float value
// return error if key not found or value is invalid type // return error if key not found or value is invalid type
func (c *configContainer) Float(ctx context.Context, key string) (float64, error) { func (c *configContainer) Float(key string) (float64, error) {
res, err := c.get(key) res, err := c.get(key)
if err != nil { if err != nil {
return 0, err return 0, err
@ -180,7 +179,7 @@ func (c *configContainer) Float(ctx context.Context, key string) (float64, error
// DefaultString return string value // DefaultString return string value
// return default value if key not found or value is invalid type // return default value if key not found or value is invalid type
func (c *configContainer) DefaultString(ctx context.Context, key string, defaultVal string) string { func (c *configContainer) DefaultString(key string, defaultVal string) string {
res, err := c.get(key) res, err := c.get(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
@ -194,7 +193,7 @@ func (c *configContainer) DefaultString(ctx context.Context, key string, default
// DefaultStrings return []string // DefaultStrings return []string
// return default value if key not found or value is invalid type // return default value if key not found or value is invalid type
func (c *configContainer) DefaultStrings(ctx context.Context, key string, defaultVal []string) []string { func (c *configContainer) DefaultStrings(key string, defaultVal []string) []string {
val, err := c.get(key) val, err := c.get(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
@ -216,13 +215,13 @@ func (c *configContainer) DefaultStrings(ctx context.Context, key string, defaul
// DefaultInt return int value // DefaultInt return int value
// return default value if key not found or value is invalid type // return default value if key not found or value is invalid type
func (c *configContainer) DefaultInt(ctx context.Context, key string, defaultVal int) int { func (c *configContainer) DefaultInt(key string, defaultVal int) int {
return int(c.DefaultInt64(ctx, key, int64(defaultVal))) return int(c.DefaultInt64(key, int64(defaultVal)))
} }
// DefaultInt64 return int64 value // DefaultInt64 return int64 value
// return default value if key not found or value is invalid type // return default value if key not found or value is invalid type
func (c *configContainer) DefaultInt64(ctx context.Context, key string, defaultVal int64) int64 { func (c *configContainer) DefaultInt64(key string, defaultVal int64) int64 {
res, err := c.get(key) res, err := c.get(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
@ -238,7 +237,7 @@ func (c *configContainer) DefaultInt64(ctx context.Context, key string, defaultV
// DefaultBool return bool value // DefaultBool return bool value
// return default value if key not found or value is invalid type // return default value if key not found or value is invalid type
func (c *configContainer) DefaultBool(ctx context.Context, key string, defaultVal bool) bool { func (c *configContainer) DefaultBool(key string, defaultVal bool) bool {
res, err := c.get(key) res, err := c.get(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
@ -252,7 +251,7 @@ func (c *configContainer) DefaultBool(ctx context.Context, key string, defaultVa
// DefaultFloat return float value // DefaultFloat return float value
// return default value if key not found or value is invalid type // return default value if key not found or value is invalid type
func (c *configContainer) DefaultFloat(ctx context.Context, key string, defaultVal float64) float64 { func (c *configContainer) DefaultFloat(key string, defaultVal float64) float64 {
res, err := c.get(key) res, err := c.get(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
@ -265,12 +264,12 @@ func (c *configContainer) DefaultFloat(ctx context.Context, key string, defaultV
} }
// DIY returns the original value // DIY returns the original value
func (c *configContainer) DIY(ctx context.Context, key string) (interface{}, error) { func (c *configContainer) DIY(key string) (interface{}, error) {
return c.get(key) return c.get(key)
} }
// GetSection return error if the value is not valid toml doc // GetSection return error if the value is not valid toml doc
func (c *configContainer) GetSection(ctx context.Context, section string) (map[string]string, error) { func (c *configContainer) GetSection(section string) (map[string]string, error) {
val, err := subTree(c.t, strings.Split(section, keySeparator)) val, err := subTree(c.t, strings.Split(section, keySeparator))
if err != nil { if err != nil {
return map[string]string{}, err return map[string]string{}, err
@ -283,7 +282,7 @@ func (c *configContainer) GetSection(ctx context.Context, section string) (map[s
return res, nil return res, nil
} }
func (c *configContainer) Unmarshaler(ctx context.Context, prefix string, obj interface{}, opt ...config.DecodeOption) error { func (c *configContainer) Unmarshaler(prefix string, obj interface{}, opt ...config.DecodeOption) error {
if len(prefix) > 0 { if len(prefix) > 0 {
t, err := subTree(c.t, strings.Split(prefix, keySeparator)) t, err := subTree(c.t, strings.Split(prefix, keySeparator))
if err != nil { if err != nil {
@ -296,7 +295,7 @@ func (c *configContainer) Unmarshaler(ctx context.Context, prefix string, obj in
// Sub return sub configer // Sub return sub configer
// return error if key not found or the value is not a sub doc // return error if key not found or the value is not a sub doc
func (c *configContainer) Sub(ctx context.Context, key string) (config.Configer, error) { func (c *configContainer) Sub(key string) (config.Configer, error) {
val, err := subTree(c.t, strings.Split(key, keySeparator)) val, err := subTree(c.t, strings.Split(key, keySeparator))
if err != nil { if err != nil {
return nil, err return nil, err
@ -307,12 +306,12 @@ func (c *configContainer) Sub(ctx context.Context, key string) (config.Configer,
} }
// OnChange do nothing // OnChange do nothing
func (c *configContainer) OnChange(ctx context.Context, key string, fn func(value string)) { func (c *configContainer) OnChange(key string, fn func(value string)) {
// do nothing // do nothing
} }
// SaveConfigFile create or override the file // SaveConfigFile create or override the file
func (c *configContainer) SaveConfigFile(ctx context.Context, filename string) error { func (c *configContainer) SaveConfigFile(filename string) error {
// Write configuration file by filename. // Write configuration file by filename.
f, err := os.Create(filename) f, err := os.Create(filename)
if err != nil { if err != nil {

View File

@ -15,7 +15,6 @@
package toml package toml
import ( import (
"context"
"fmt" "fmt"
"os" "os"
"testing" "testing"
@ -52,11 +51,11 @@ Woman="true"
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, c) assert.NotNil(t, c)
val, err := c.Bool(context.Background(), "Man") val, err := c.Bool("Man")
assert.Nil(t, err) assert.Nil(t, err)
assert.True(t, val) assert.True(t, val)
_, err = c.Bool(context.Background(), "Woman") _, err = c.Bool("Woman")
assert.NotNil(t, err) assert.NotNil(t, err)
assert.Equal(t, config.InvalidValueTypeError, err) assert.Equal(t, config.InvalidValueTypeError, err)
} }
@ -71,13 +70,13 @@ Woman="false"
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, c) assert.NotNil(t, c)
val := c.DefaultBool(context.Background(), "Man11", true) val := c.DefaultBool("Man11", true)
assert.True(t, val) assert.True(t, val)
val = c.DefaultBool(context.Background(), "Man", false) val = c.DefaultBool("Man", false)
assert.True(t, val) assert.True(t, val)
val = c.DefaultBool(context.Background(), "Woman", true) val = c.DefaultBool("Woman", true)
assert.True(t, val) assert.True(t, val)
} }
@ -91,13 +90,13 @@ PriceInvalid="12.3"
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, c) assert.NotNil(t, c)
val := c.DefaultFloat(context.Background(), "Price", 11.2) val := c.DefaultFloat("Price", 11.2)
assert.Equal(t, 12.3, val) assert.Equal(t, 12.3, val)
val = c.DefaultFloat(context.Background(), "Price11", 11.2) val = c.DefaultFloat("Price11", 11.2)
assert.Equal(t, 11.2, val) assert.Equal(t, 11.2, val)
val = c.DefaultFloat(context.Background(), "PriceInvalid", 11.2) val = c.DefaultFloat("PriceInvalid", 11.2)
assert.Equal(t, 11.2, val) assert.Equal(t, 11.2, val)
} }
@ -111,13 +110,13 @@ AgeInvalid="13"
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, c) assert.NotNil(t, c)
val := c.DefaultInt(context.Background(), "Age", 11) val := c.DefaultInt("Age", 11)
assert.Equal(t, 12, val) assert.Equal(t, 12, val)
val = c.DefaultInt(context.Background(), "Price11", 11) val = c.DefaultInt("Price11", 11)
assert.Equal(t, 11, val) assert.Equal(t, 11, val)
val = c.DefaultInt(context.Background(), "PriceInvalid", 11) val = c.DefaultInt("PriceInvalid", 11)
assert.Equal(t, 11, val) assert.Equal(t, 11, val)
} }
@ -131,13 +130,13 @@ NameInvalid=13
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, c) assert.NotNil(t, c)
val := c.DefaultString(context.Background(), "Name", "Jerry") val := c.DefaultString("Name", "Jerry")
assert.Equal(t, "Tom", val) assert.Equal(t, "Tom", val)
val = c.DefaultString(context.Background(), "Name11", "Jerry") val = c.DefaultString("Name11", "Jerry")
assert.Equal(t, "Jerry", val) assert.Equal(t, "Jerry", val)
val = c.DefaultString(context.Background(), "NameInvalid", "Jerry") val = c.DefaultString("NameInvalid", "Jerry")
assert.Equal(t, "Jerry", val) assert.Equal(t, "Jerry", val)
} }
@ -151,13 +150,13 @@ NameInvalid="Tom"
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, c) assert.NotNil(t, c)
val := c.DefaultStrings(context.Background(), "Name", []string{"Jerry"}) val := c.DefaultStrings("Name", []string{"Jerry"})
assert.Equal(t, []string{"Tom", "Jerry"}, val) assert.Equal(t, []string{"Tom", "Jerry"}, val)
val = c.DefaultStrings(context.Background(), "Name11", []string{"Jerry"}) val = c.DefaultStrings("Name11", []string{"Jerry"})
assert.Equal(t, []string{"Jerry"}, val) assert.Equal(t, []string{"Jerry"}, val)
val = c.DefaultStrings(context.Background(), "NameInvalid", []string{"Jerry"}) val = c.DefaultStrings("NameInvalid", []string{"Jerry"})
assert.Equal(t, []string{"Jerry"}, val) assert.Equal(t, []string{"Jerry"}, val)
} }
@ -170,7 +169,7 @@ Name=["Tom", "Jerry"]
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, c) assert.NotNil(t, c)
_, err = c.DIY(context.Background(), "Name") _, err = c.DIY("Name")
assert.Nil(t, err) assert.Nil(t, err)
} }
@ -184,14 +183,14 @@ PriceInvalid="12.3"
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, c) assert.NotNil(t, c)
val, err := c.Float(context.Background(), "Price") val, err := c.Float("Price")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, 12.3, val) assert.Equal(t, 12.3, val)
_, err = c.Float(context.Background(), "Price11") _, err = c.Float("Price11")
assert.Equal(t, config.KeyNotFoundError, err) assert.Equal(t, config.KeyNotFoundError, err)
_, err = c.Float(context.Background(), "PriceInvalid") _, err = c.Float("PriceInvalid")
assert.Equal(t, config.InvalidValueTypeError, err) assert.Equal(t, config.InvalidValueTypeError, err)
} }
@ -205,14 +204,14 @@ AgeInvalid="13"
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, c) assert.NotNil(t, c)
val, err := c.Int(context.Background(), "Age") val, err := c.Int("Age")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, 12, val) assert.Equal(t, 12, val)
_, err = c.Int(context.Background(), "Age11") _, err = c.Int("Age11")
assert.Equal(t, config.KeyNotFoundError, err) assert.Equal(t, config.KeyNotFoundError, err)
_, err = c.Int(context.Background(), "AgeInvalid") _, err = c.Int("AgeInvalid")
assert.Equal(t, config.InvalidValueTypeError, err) assert.Equal(t, config.InvalidValueTypeError, err)
} }
@ -234,7 +233,7 @@ func TestConfigContainer_GetSection(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, c) assert.NotNil(t, c)
m, err := c.GetSection(context.Background(), "servers") m, err := c.GetSection("servers")
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, m) assert.NotNil(t, m)
assert.Equal(t, 2, len(m)) assert.Equal(t, 2, len(m))
@ -252,17 +251,17 @@ Name="Jerry"
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, c) assert.NotNil(t, c)
val, err := c.String(context.Background(), "Name") val, err := c.String("Name")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "Tom", val) assert.Equal(t, "Tom", val)
_, err = c.String(context.Background(), "Name11") _, err = c.String("Name11")
assert.Equal(t, config.KeyNotFoundError, err) assert.Equal(t, config.KeyNotFoundError, err)
_, err = c.String(context.Background(), "NameInvalid") _, err = c.String("NameInvalid")
assert.Equal(t, config.InvalidValueTypeError, err) assert.Equal(t, config.InvalidValueTypeError, err)
val, err = c.String(context.Background(), "Person.Name") val, err = c.String("Person.Name")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "Jerry", val) assert.Equal(t, "Jerry", val)
} }
@ -277,14 +276,14 @@ NameInvalid="Tom"
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, c) assert.NotNil(t, c)
val, err := c.Strings(context.Background(), "Name") val, err := c.Strings("Name")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, []string{"Tom", "Jerry"}, val) assert.Equal(t, []string{"Tom", "Jerry"}, val)
_, err = c.Strings(context.Background(), "Name11") _, err = c.Strings("Name11")
assert.Equal(t, config.KeyNotFoundError, err) assert.Equal(t, config.KeyNotFoundError, err)
_, err = c.Strings(context.Background(), "NameInvalid") _, err = c.Strings("NameInvalid")
assert.Equal(t, config.InvalidValueTypeError, err) assert.Equal(t, config.InvalidValueTypeError, err)
} }
@ -298,9 +297,9 @@ NameInvalid="Tom"
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, c) assert.NotNil(t, c)
err = c.Set(context.Background(), "Age", "11") err = c.Set("Age", "11")
assert.Nil(t, err) assert.Nil(t, err)
age, err := c.String(context.Background(), "Age") age, err := c.String("Age")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "11", age) assert.Equal(t, "11", age)
} }
@ -323,24 +322,24 @@ func TestConfigContainer_SubAndMushall(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, c) assert.NotNil(t, c)
sub, err := c.Sub(context.Background(), "servers") sub, err := c.Sub("servers")
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, sub) assert.NotNil(t, sub)
sub, err = sub.Sub(context.Background(), "alpha") sub, err = sub.Sub("alpha")
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, sub) assert.NotNil(t, sub)
ip, err := sub.String(context.Background(), "ip") ip, err := sub.String("ip")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "10.0.0.1", ip) assert.Equal(t, "10.0.0.1", ip)
svr := &Server{} svr := &Server{}
err = sub.Unmarshaler(context.Background(), "", svr) err = sub.Unmarshaler("", svr)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "10.0.0.1", svr.Ip) assert.Equal(t, "10.0.0.1", svr.Ip)
svr = &Server{} svr = &Server{}
err = c.Unmarshaler(context.Background(), "servers.alpha", svr) err = c.Unmarshaler("servers.alpha", svr)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "10.0.0.1", svr.Ip) assert.Equal(t, "10.0.0.1", svr.Ip)
} }
@ -368,10 +367,10 @@ func TestConfigContainer_SaveConfigFile(t *testing.T) {
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, c) assert.NotNil(t, c)
sub, err := c.Sub(context.Background(), "servers") sub, err := c.Sub("servers")
assert.Nil(t, err) assert.Nil(t, err)
err = sub.SaveConfigFile(context.Background(), path) err = sub.SaveConfigFile(path)
assert.Nil(t, err) assert.Nil(t, err)
} }

View File

@ -30,7 +30,6 @@
package xml package xml
import ( import (
"context"
"encoding/xml" "encoding/xml"
"errors" "errors"
"fmt" "fmt"
@ -87,16 +86,16 @@ type ConfigContainer struct {
// So when you use // So when you use
// <id>1</id> // <id>1</id>
// The "1" is a string, not int // The "1" is a string, not int
func (c *ConfigContainer) Unmarshaler(ctx context.Context, prefix string, obj interface{}, opt ...config.DecodeOption) error { func (c *ConfigContainer) Unmarshaler(prefix string, obj interface{}, opt ...config.DecodeOption) error {
sub, err := c.sub(ctx, prefix) sub, err := c.sub(prefix)
if err != nil { if err != nil {
return err return err
} }
return mapstructure.Decode(sub, obj) return mapstructure.Decode(sub, obj)
} }
func (c *ConfigContainer) Sub(ctx context.Context, key string) (config.Configer, error) { func (c *ConfigContainer) Sub(key string) (config.Configer, error) {
sub, err := c.sub(ctx, key) sub, err := c.sub(key)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -107,7 +106,7 @@ func (c *ConfigContainer) Sub(ctx context.Context, key string) (config.Configer,
} }
func (c *ConfigContainer) sub(ctx context.Context, key string) (map[string]interface{}, error) { func (c *ConfigContainer) sub(key string) (map[string]interface{}, error) {
if key == "" { if key == "" {
return c.data, nil return c.data, nil
} }
@ -122,12 +121,12 @@ func (c *ConfigContainer) sub(ctx context.Context, key string) (map[string]inter
return res, nil return res, nil
} }
func (c *ConfigContainer) OnChange(ctx context.Context, key string, fn func(value string)) { func (c *ConfigContainer) OnChange(key string, fn func(value string)) {
logs.Warn("Unsupported operation") logs.Warn("Unsupported operation")
} }
// Bool returns the boolean value for a given key. // Bool returns the boolean value for a given key.
func (c *ConfigContainer) Bool(ctx context.Context, key string) (bool, error) { func (c *ConfigContainer) Bool(key string) (bool, error) {
if v := c.data[key]; v != nil { if v := c.data[key]; v != nil {
return config.ParseBool(v) return config.ParseBool(v)
} }
@ -136,8 +135,8 @@ func (c *ConfigContainer) Bool(ctx context.Context, key string) (bool, error) {
// DefaultBool return the bool value if has no error // DefaultBool return the bool value if has no error
// otherwise return the defaultVal // otherwise return the defaultVal
func (c *ConfigContainer) DefaultBool(ctx context.Context, key string, defaultVal bool) bool { func (c *ConfigContainer) DefaultBool(key string, defaultVal bool) bool {
v, err := c.Bool(ctx, key) v, err := c.Bool(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
} }
@ -145,14 +144,14 @@ func (c *ConfigContainer) DefaultBool(ctx context.Context, key string, defaultVa
} }
// Int returns the integer value for a given key. // Int returns the integer value for a given key.
func (c *ConfigContainer) Int(ctx context.Context, key string) (int, error) { func (c *ConfigContainer) Int(key string) (int, error) {
return strconv.Atoi(c.data[key].(string)) return strconv.Atoi(c.data[key].(string))
} }
// DefaultInt returns the integer value for a given key. // DefaultInt returns the integer value for a given key.
// if err != nil return defaultVal // if err != nil return defaultVal
func (c *ConfigContainer) DefaultInt(ctx context.Context, key string, defaultVal int) int { func (c *ConfigContainer) DefaultInt(key string, defaultVal int) int {
v, err := c.Int(ctx, key) v, err := c.Int(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
} }
@ -160,14 +159,14 @@ func (c *ConfigContainer) DefaultInt(ctx context.Context, key string, defaultVal
} }
// Int64 returns the int64 value for a given key. // Int64 returns the int64 value for a given key.
func (c *ConfigContainer) Int64(ctx context.Context, key string) (int64, error) { func (c *ConfigContainer) Int64(key string) (int64, error) {
return strconv.ParseInt(c.data[key].(string), 10, 64) return strconv.ParseInt(c.data[key].(string), 10, 64)
} }
// DefaultInt64 returns the int64 value for a given key. // DefaultInt64 returns the int64 value for a given key.
// if err != nil return defaultVal // if err != nil return defaultVal
func (c *ConfigContainer) DefaultInt64(ctx context.Context, key string, defaultVal int64) int64 { func (c *ConfigContainer) DefaultInt64(key string, defaultVal int64) int64 {
v, err := c.Int64(ctx, key) v, err := c.Int64(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
} }
@ -176,14 +175,14 @@ func (c *ConfigContainer) DefaultInt64(ctx context.Context, key string, defaultV
} }
// Float returns the float value for a given key. // Float returns the float value for a given key.
func (c *ConfigContainer) Float(ctx context.Context, key string) (float64, error) { func (c *ConfigContainer) Float(key string) (float64, error) {
return strconv.ParseFloat(c.data[key].(string), 64) return strconv.ParseFloat(c.data[key].(string), 64)
} }
// DefaultFloat returns the float64 value for a given key. // DefaultFloat returns the float64 value for a given key.
// if err != nil return defaultVal // if err != nil return defaultVal
func (c *ConfigContainer) DefaultFloat(ctx context.Context, key string, defaultVal float64) float64 { func (c *ConfigContainer) DefaultFloat(key string, defaultVal float64) float64 {
v, err := c.Float(ctx, key) v, err := c.Float(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
} }
@ -191,7 +190,7 @@ func (c *ConfigContainer) DefaultFloat(ctx context.Context, key string, defaultV
} }
// String returns the string value for a given key. // String returns the string value for a given key.
func (c *ConfigContainer) String(ctx context.Context, key string) (string, error) { func (c *ConfigContainer) String(key string) (string, error) {
if v, ok := c.data[key].(string); ok { if v, ok := c.data[key].(string); ok {
return v, nil return v, nil
} }
@ -200,8 +199,8 @@ func (c *ConfigContainer) String(ctx context.Context, key string) (string, error
// DefaultString returns the string value for a given key. // DefaultString returns the string value for a given key.
// if err != nil return defaultVal // if err != nil return defaultVal
func (c *ConfigContainer) DefaultString(ctx context.Context, key string, defaultVal string) string { func (c *ConfigContainer) DefaultString(key string, defaultVal string) string {
v, err := c.String(ctx, key) v, err := c.String(key)
if v == "" || err != nil { if v == "" || err != nil {
return defaultVal return defaultVal
} }
@ -209,8 +208,8 @@ func (c *ConfigContainer) DefaultString(ctx context.Context, key string, default
} }
// Strings returns the []string value for a given key. // Strings returns the []string value for a given key.
func (c *ConfigContainer) Strings(ctx context.Context, key string) ([]string, error) { func (c *ConfigContainer) Strings(key string) ([]string, error) {
v, err := c.String(ctx, key) v, err := c.String(key)
if v == "" || err != nil { if v == "" || err != nil {
return nil, err return nil, err
} }
@ -219,8 +218,8 @@ func (c *ConfigContainer) Strings(ctx context.Context, key string) ([]string, er
// DefaultStrings returns the []string value for a given key. // DefaultStrings returns the []string value for a given key.
// if err != nil return defaultVal // if err != nil return defaultVal
func (c *ConfigContainer) DefaultStrings(ctx context.Context, key string, defaultVal []string) []string { func (c *ConfigContainer) DefaultStrings(key string, defaultVal []string) []string {
v, err := c.Strings(ctx, key) v, err := c.Strings(key)
if v == nil || err != nil { if v == nil || err != nil {
return defaultVal return defaultVal
} }
@ -228,7 +227,7 @@ func (c *ConfigContainer) DefaultStrings(ctx context.Context, key string, defaul
} }
// GetSection returns map for the given section // GetSection returns map for the given section
func (c *ConfigContainer) GetSection(ctx context.Context, section string) (map[string]string, error) { func (c *ConfigContainer) GetSection(section string) (map[string]string, error) {
if v, ok := c.data[section].(map[string]interface{}); ok { if v, ok := c.data[section].(map[string]interface{}); ok {
mapstr := make(map[string]string) mapstr := make(map[string]string)
for k, val := range v { for k, val := range v {
@ -240,7 +239,7 @@ func (c *ConfigContainer) GetSection(ctx context.Context, section string) (map[s
} }
// SaveConfigFile save the config into file // SaveConfigFile save the config into file
func (c *ConfigContainer) SaveConfigFile(ctx context.Context, filename string) (err error) { func (c *ConfigContainer) SaveConfigFile(filename string) (err error) {
// Write configuration file by filename. // Write configuration file by filename.
f, err := os.Create(filename) f, err := os.Create(filename)
if err != nil { if err != nil {
@ -256,7 +255,7 @@ func (c *ConfigContainer) SaveConfigFile(ctx context.Context, filename string) (
} }
// Set writes a new value for key. // Set writes a new value for key.
func (c *ConfigContainer) Set(ctx context.Context, key, val string) error { func (c *ConfigContainer) Set(key, val string) error {
c.Lock() c.Lock()
defer c.Unlock() defer c.Unlock()
c.data[key] = val c.data[key] = val
@ -264,7 +263,7 @@ func (c *ConfigContainer) Set(ctx context.Context, key, val string) error {
} }
// DIY returns the raw value by a given key. // DIY returns the raw value by a given key.
func (c *ConfigContainer) DIY(ctx context.Context, key string) (v interface{}, err error) { func (c *ConfigContainer) DIY(key string) (v interface{}, err error) {
if v, ok := c.data[key]; ok { if v, ok := c.data[key]; ok {
return v, nil return v, nil
} }

View File

@ -15,7 +15,6 @@
package xml package xml
import ( import (
"context"
"fmt" "fmt"
"os" "os"
"testing" "testing"
@ -79,7 +78,7 @@ func TestXML(t *testing.T) {
} }
var xmlsection map[string]string var xmlsection map[string]string
xmlsection, err = xmlconf.GetSection(nil, "mysection") xmlsection, err = xmlconf.GetSection("mysection")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -97,19 +96,19 @@ func TestXML(t *testing.T) {
switch v.(type) { switch v.(type) {
case int: case int:
value, err = xmlconf.Int(nil, k) value, err = xmlconf.Int(k)
case int64: case int64:
value, err = xmlconf.Int64(nil, k) value, err = xmlconf.Int64(k)
case float64: case float64:
value, err = xmlconf.Float(nil, k) value, err = xmlconf.Float(k)
case bool: case bool:
value, err = xmlconf.Bool(nil, k) value, err = xmlconf.Bool(k)
case []string: case []string:
value, err = xmlconf.Strings(nil, k) value, err = xmlconf.Strings(k)
case string: case string:
value, err = xmlconf.String(nil, k) value, err = xmlconf.String(k)
default: default:
value, err = xmlconf.DIY(nil, k) value, err = xmlconf.DIY(k)
} }
if err != nil { if err != nil {
t.Errorf("get key %q value fatal,%v err %s", k, v, err) t.Errorf("get key %q value fatal,%v err %s", k, v, err)
@ -119,35 +118,35 @@ func TestXML(t *testing.T) {
} }
if err = xmlconf.Set(nil, "name", "astaxie"); err != nil { if err = xmlconf.Set("name", "astaxie"); err != nil {
t.Fatal(err) t.Fatal(err)
} }
res, _ := xmlconf.String(context.Background(), "name") res, _ := xmlconf.String("name")
if res != "astaxie" { if res != "astaxie" {
t.Fatal("get name error") t.Fatal("get name error")
} }
sub, err := xmlconf.Sub(context.Background(), "mysection") sub, err := xmlconf.Sub("mysection")
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, sub) assert.NotNil(t, sub)
name, err := sub.String(context.Background(), "name") name, err := sub.String("name")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "MySection", name) assert.Equal(t, "MySection", name)
id, err := sub.Int(context.Background(), "id") id, err := sub.Int("id")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, 1, id) assert.Equal(t, 1, id)
sec := &Section{} sec := &Section{}
err = sub.Unmarshaler(context.Background(), "", sec) err = sub.Unmarshaler("", sec)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "MySection", sec.Name) assert.Equal(t, "MySection", sec.Name)
sec = &Section{} sec = &Section{}
err = xmlconf.Unmarshaler(context.Background(), "mysection", sec) err = xmlconf.Unmarshaler("mysection", sec)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "MySection", sec.Name) assert.Equal(t, "MySection", sec.Name)

View File

@ -31,7 +31,6 @@ package yaml
import ( import (
"bytes" "bytes"
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@ -41,10 +40,11 @@ import (
"strings" "strings"
"sync" "sync"
"github.com/astaxie/beego/core/config"
"github.com/astaxie/beego/core/logs"
"github.com/beego/goyaml2" "github.com/beego/goyaml2"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
"github.com/astaxie/beego/core/config"
"github.com/astaxie/beego/core/logs"
) )
// Config is a yaml config parser and implements Config interface. // Config is a yaml config parser and implements Config interface.
@ -126,8 +126,8 @@ type ConfigContainer struct {
} }
// Unmarshaler is similar to Sub // Unmarshaler is similar to Sub
func (c *ConfigContainer) Unmarshaler(ctx context.Context, prefix string, obj interface{}, opt ...config.DecodeOption) error { func (c *ConfigContainer) Unmarshaler(prefix string, obj interface{}, opt ...config.DecodeOption) error {
sub, err := c.sub(ctx, prefix) sub, err := c.sub(prefix)
if err != nil { if err != nil {
return err return err
} }
@ -139,8 +139,8 @@ func (c *ConfigContainer) Unmarshaler(ctx context.Context, prefix string, obj in
return yaml.Unmarshal(bytes, obj) return yaml.Unmarshal(bytes, obj)
} }
func (c *ConfigContainer) Sub(ctx context.Context, key string) (config.Configer, error) { func (c *ConfigContainer) Sub(key string) (config.Configer, error) {
sub, err := c.sub(ctx, key) sub, err := c.sub(key)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -149,7 +149,7 @@ func (c *ConfigContainer) Sub(ctx context.Context, key string) (config.Configer,
}, nil }, nil
} }
func (c *ConfigContainer) sub(ctx context.Context, key string) (map[string]interface{}, error) { func (c *ConfigContainer) sub(key string) (map[string]interface{}, error) {
tmpData := c.data tmpData := c.data
keys := strings.Split(key, ".") keys := strings.Split(key, ".")
for idx, k := range keys { for idx, k := range keys {
@ -171,13 +171,13 @@ func (c *ConfigContainer) sub(ctx context.Context, key string) (map[string]inter
return tmpData, nil return tmpData, nil
} }
func (c *ConfigContainer) OnChange(ctx context.Context, key string, fn func(value string)) { func (c *ConfigContainer) OnChange(key string, fn func(value string)) {
// do nothing // do nothing
logs.Warn("Unsupported operation: OnChange") logs.Warn("Unsupported operation: OnChange")
} }
// Bool returns the boolean value for a given key. // Bool returns the boolean value for a given key.
func (c *ConfigContainer) Bool(ctx context.Context, key string) (bool, error) { func (c *ConfigContainer) Bool(key string) (bool, error) {
v, err := c.getData(key) v, err := c.getData(key)
if err != nil { if err != nil {
return false, err return false, err
@ -187,8 +187,8 @@ func (c *ConfigContainer) Bool(ctx context.Context, key string) (bool, error) {
// DefaultBool return the bool value if has no error // DefaultBool return the bool value if has no error
// otherwise return the defaultVal // otherwise return the defaultVal
func (c *ConfigContainer) DefaultBool(ctx context.Context, key string, defaultVal bool) bool { func (c *ConfigContainer) DefaultBool(key string, defaultVal bool) bool {
v, err := c.Bool(ctx, key) v, err := c.Bool(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
} }
@ -196,7 +196,7 @@ func (c *ConfigContainer) DefaultBool(ctx context.Context, key string, defaultVa
} }
// Int returns the integer value for a given key. // Int returns the integer value for a given key.
func (c *ConfigContainer) Int(ctx context.Context, key string) (int, error) { func (c *ConfigContainer) Int(key string) (int, error) {
if v, err := c.getData(key); err != nil { if v, err := c.getData(key); err != nil {
return 0, err return 0, err
} else if vv, ok := v.(int); ok { } else if vv, ok := v.(int); ok {
@ -209,8 +209,8 @@ func (c *ConfigContainer) Int(ctx context.Context, key string) (int, error) {
// DefaultInt returns the integer value for a given key. // DefaultInt returns the integer value for a given key.
// if err != nil return defaultVal // if err != nil return defaultVal
func (c *ConfigContainer) DefaultInt(ctx context.Context, key string, defaultVal int) int { func (c *ConfigContainer) DefaultInt(key string, defaultVal int) int {
v, err := c.Int(ctx, key) v, err := c.Int(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
} }
@ -218,7 +218,7 @@ func (c *ConfigContainer) DefaultInt(ctx context.Context, key string, defaultVal
} }
// Int64 returns the int64 value for a given key. // Int64 returns the int64 value for a given key.
func (c *ConfigContainer) Int64(ctx context.Context, key string) (int64, error) { func (c *ConfigContainer) Int64(key string) (int64, error) {
if v, err := c.getData(key); err != nil { if v, err := c.getData(key); err != nil {
return 0, err return 0, err
} else if vv, ok := v.(int64); ok { } else if vv, ok := v.(int64); ok {
@ -229,8 +229,8 @@ func (c *ConfigContainer) Int64(ctx context.Context, key string) (int64, error)
// DefaultInt64 returns the int64 value for a given key. // DefaultInt64 returns the int64 value for a given key.
// if err != nil return defaultVal // if err != nil return defaultVal
func (c *ConfigContainer) DefaultInt64(ctx context.Context, key string, defaultVal int64) int64 { func (c *ConfigContainer) DefaultInt64(key string, defaultVal int64) int64 {
v, err := c.Int64(ctx, key) v, err := c.Int64(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
} }
@ -238,7 +238,7 @@ func (c *ConfigContainer) DefaultInt64(ctx context.Context, key string, defaultV
} }
// Float returns the float value for a given key. // Float returns the float value for a given key.
func (c *ConfigContainer) Float(ctx context.Context, key string) (float64, error) { func (c *ConfigContainer) Float(key string) (float64, error) {
if v, err := c.getData(key); err != nil { if v, err := c.getData(key); err != nil {
return 0.0, err return 0.0, err
} else if vv, ok := v.(float64); ok { } else if vv, ok := v.(float64); ok {
@ -253,8 +253,8 @@ func (c *ConfigContainer) Float(ctx context.Context, key string) (float64, error
// DefaultFloat returns the float64 value for a given key. // DefaultFloat returns the float64 value for a given key.
// if err != nil return defaultVal // if err != nil return defaultVal
func (c *ConfigContainer) DefaultFloat(ctx context.Context, key string, defaultVal float64) float64 { func (c *ConfigContainer) DefaultFloat(key string, defaultVal float64) float64 {
v, err := c.Float(ctx, key) v, err := c.Float(key)
if err != nil { if err != nil {
return defaultVal return defaultVal
} }
@ -262,7 +262,7 @@ func (c *ConfigContainer) DefaultFloat(ctx context.Context, key string, defaultV
} }
// String returns the string value for a given key. // String returns the string value for a given key.
func (c *ConfigContainer) String(ctx context.Context, key string) (string, error) { func (c *ConfigContainer) String(key string) (string, error) {
if v, err := c.getData(key); err == nil { if v, err := c.getData(key); err == nil {
if vv, ok := v.(string); ok { if vv, ok := v.(string); ok {
return vv, nil return vv, nil
@ -273,8 +273,8 @@ func (c *ConfigContainer) String(ctx context.Context, key string) (string, error
// DefaultString returns the string value for a given key. // DefaultString returns the string value for a given key.
// if err != nil return defaultVal // if err != nil return defaultVal
func (c *ConfigContainer) DefaultString(ctx context.Context, key string, defaultVal string) string { func (c *ConfigContainer) DefaultString(key string, defaultVal string) string {
v, err := c.String(nil, key) v, err := c.String(key)
if v == "" || err != nil { if v == "" || err != nil {
return defaultVal return defaultVal
} }
@ -282,8 +282,8 @@ func (c *ConfigContainer) DefaultString(ctx context.Context, key string, default
} }
// Strings returns the []string value for a given key. // Strings returns the []string value for a given key.
func (c *ConfigContainer) Strings(ctx context.Context, key string) ([]string, error) { func (c *ConfigContainer) Strings(key string) ([]string, error) {
v, err := c.String(nil, key) v, err := c.String(key)
if v == "" || err != nil { if v == "" || err != nil {
return nil, err return nil, err
} }
@ -292,8 +292,8 @@ func (c *ConfigContainer) Strings(ctx context.Context, key string) ([]string, er
// DefaultStrings returns the []string value for a given key. // DefaultStrings returns the []string value for a given key.
// if err != nil return defaultVal // if err != nil return defaultVal
func (c *ConfigContainer) DefaultStrings(ctx context.Context, key string, defaultVal []string) []string { func (c *ConfigContainer) DefaultStrings(key string, defaultVal []string) []string {
v, err := c.Strings(ctx, key) v, err := c.Strings(key)
if v == nil || err != nil { if v == nil || err != nil {
return defaultVal return defaultVal
} }
@ -301,7 +301,7 @@ func (c *ConfigContainer) DefaultStrings(ctx context.Context, key string, defaul
} }
// GetSection returns map for the given section // GetSection returns map for the given section
func (c *ConfigContainer) GetSection(ctx context.Context, section string) (map[string]string, error) { func (c *ConfigContainer) GetSection(section string) (map[string]string, error) {
if v, ok := c.data[section]; ok { if v, ok := c.data[section]; ok {
return v.(map[string]string), nil return v.(map[string]string), nil
@ -310,7 +310,7 @@ func (c *ConfigContainer) GetSection(ctx context.Context, section string) (map[s
} }
// SaveConfigFile save the config into file // SaveConfigFile save the config into file
func (c *ConfigContainer) SaveConfigFile(ctx context.Context, filename string) (err error) { func (c *ConfigContainer) SaveConfigFile(filename string) (err error) {
// Write configuration file by filename. // Write configuration file by filename.
f, err := os.Create(filename) f, err := os.Create(filename)
if err != nil { if err != nil {
@ -322,7 +322,7 @@ func (c *ConfigContainer) SaveConfigFile(ctx context.Context, filename string) (
} }
// Set writes a new value for key. // Set writes a new value for key.
func (c *ConfigContainer) Set(ctx context.Context, key, val string) error { func (c *ConfigContainer) Set(key, val string) error {
c.Lock() c.Lock()
defer c.Unlock() defer c.Unlock()
c.data[key] = val c.data[key] = val
@ -330,7 +330,7 @@ func (c *ConfigContainer) Set(ctx context.Context, key, val string) error {
} }
// DIY returns the raw value by a given key. // DIY returns the raw value by a given key.
func (c *ConfigContainer) DIY(ctx context.Context, key string) (v interface{}, err error) { func (c *ConfigContainer) DIY(key string) (v interface{}, err error) {
return c.getData(key) return c.getData(key)
} }

View File

@ -15,7 +15,6 @@
package yaml package yaml
import ( import (
"context"
"fmt" "fmt"
"os" "os"
"testing" "testing"
@ -76,7 +75,7 @@ func TestYaml(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
res, _ := yamlconf.String(nil, "appname") res, _ := yamlconf.String("appname")
if res != "beeapi" { if res != "beeapi" {
t.Fatal("appname not equal to beeapi") t.Fatal("appname not equal to beeapi")
} }
@ -90,19 +89,19 @@ func TestYaml(t *testing.T) {
switch v.(type) { switch v.(type) {
case int: case int:
value, err = yamlconf.Int(nil, k) value, err = yamlconf.Int(k)
case int64: case int64:
value, err = yamlconf.Int64(nil, k) value, err = yamlconf.Int64(k)
case float64: case float64:
value, err = yamlconf.Float(nil, k) value, err = yamlconf.Float(k)
case bool: case bool:
value, err = yamlconf.Bool(nil, k) value, err = yamlconf.Bool(k)
case []string: case []string:
value, err = yamlconf.Strings(nil, k) value, err = yamlconf.Strings(k)
case string: case string:
value, err = yamlconf.String(nil, k) value, err = yamlconf.String(k)
default: default:
value, err = yamlconf.DIY(nil, k) value, err = yamlconf.DIY(k)
} }
if err != nil { if err != nil {
t.Errorf("get key %q value fatal,%v err %s", k, v, err) t.Errorf("get key %q value fatal,%v err %s", k, v, err)
@ -112,35 +111,35 @@ func TestYaml(t *testing.T) {
} }
if err = yamlconf.Set(nil, "name", "astaxie"); err != nil { if err = yamlconf.Set("name", "astaxie"); err != nil {
t.Fatal(err) t.Fatal(err)
} }
res, _ = yamlconf.String(nil, "name") res, _ = yamlconf.String("name")
if res != "astaxie" { if res != "astaxie" {
t.Fatal("get name error") t.Fatal("get name error")
} }
sub, err := yamlconf.Sub(context.Background(), "user") sub, err := yamlconf.Sub("user")
assert.Nil(t, err) assert.Nil(t, err)
assert.NotNil(t, sub) assert.NotNil(t, sub)
name, err := sub.String(context.Background(), "name") name, err := sub.String("name")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "tom", name) assert.Equal(t, "tom", name)
age, err := sub.Int(context.Background(), "age") age, err := sub.Int("age")
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, 13, age) assert.Equal(t, 13, age)
user := &User{} user := &User{}
err = sub.Unmarshaler(context.Background(), "", user) err = sub.Unmarshaler("", user)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "tom", user.Name) assert.Equal(t, "tom", user.Name)
assert.Equal(t, 13, user.Age) assert.Equal(t, 13, user.Age)
user = &User{} user = &User{}
err = yamlconf.Unmarshaler(context.Background(), "user", user) err = yamlconf.Unmarshaler("user", user)
assert.Nil(t, err) assert.Nil(t, err)
assert.Equal(t, "tom", user.Name) assert.Equal(t, "tom", user.Name)
assert.Equal(t, 13, user.Age) assert.Equal(t, 13, user.Age)

View File

@ -15,7 +15,6 @@
package web package web
import ( import (
context2 "context"
"crypto/tls" "crypto/tls"
"fmt" "fmt"
"os" "os"
@ -301,11 +300,11 @@ func assignConfig(ac config.Configer) error {
// set the run mode first // set the run mode first
if envRunMode := os.Getenv("BEEGO_RUNMODE"); envRunMode != "" { if envRunMode := os.Getenv("BEEGO_RUNMODE"); envRunMode != "" {
BConfig.RunMode = envRunMode BConfig.RunMode = envRunMode
} else if runMode, err := ac.String(nil, "RunMode"); runMode != "" && err == nil { } else if runMode, err := ac.String("RunMode"); runMode != "" && err == nil {
BConfig.RunMode = runMode BConfig.RunMode = runMode
} }
if sd, err := ac.String(nil, "StaticDir"); sd != "" && err == nil { if sd, err := ac.String("StaticDir"); sd != "" && err == nil {
BConfig.WebConfig.StaticDir = map[string]string{} BConfig.WebConfig.StaticDir = map[string]string{}
sds := strings.Fields(sd) sds := strings.Fields(sd)
for _, v := range sds { for _, v := range sds {
@ -317,7 +316,7 @@ func assignConfig(ac config.Configer) error {
} }
} }
if sgz, err := ac.String(nil, "StaticExtensionsToGzip"); sgz != "" && err == nil { if sgz, err := ac.String("StaticExtensionsToGzip"); sgz != "" && err == nil {
extensions := strings.Split(sgz, ",") extensions := strings.Split(sgz, ",")
fileExts := []string{} fileExts := []string{}
for _, ext := range extensions { for _, ext := range extensions {
@ -335,15 +334,15 @@ func assignConfig(ac config.Configer) error {
} }
} }
if sfs, err := ac.Int(nil, "StaticCacheFileSize"); err == nil { if sfs, err := ac.Int("StaticCacheFileSize"); err == nil {
BConfig.WebConfig.StaticCacheFileSize = sfs BConfig.WebConfig.StaticCacheFileSize = sfs
} }
if sfn, err := ac.Int(nil, "StaticCacheFileNum"); err == nil { if sfn, err := ac.Int("StaticCacheFileNum"); err == nil {
BConfig.WebConfig.StaticCacheFileNum = sfn BConfig.WebConfig.StaticCacheFileNum = sfn
} }
if lo, err := ac.String(nil, "LogOutputs"); lo != "" && err == nil { if lo, err := ac.String("LogOutputs"); lo != "" && err == nil {
// if lo is not nil or empty // if lo is not nil or empty
// means user has set his own LogOutputs // means user has set his own LogOutputs
// clear the default setting to BConfig.Log.Outputs // clear the default setting to BConfig.Log.Outputs
@ -390,11 +389,11 @@ func assignSingleConfig(p interface{}, ac config.Configer) {
name := pt.Field(i).Name name := pt.Field(i).Name
switch pf.Kind() { switch pf.Kind() {
case reflect.String: case reflect.String:
pf.SetString(ac.DefaultString(nil, name, pf.String())) pf.SetString(ac.DefaultString(name, pf.String()))
case reflect.Int, reflect.Int64: case reflect.Int, reflect.Int64:
pf.SetInt(ac.DefaultInt64(nil, name, pf.Int())) pf.SetInt(ac.DefaultInt64(name, pf.Int()))
case reflect.Bool: case reflect.Bool:
pf.SetBool(ac.DefaultBool(nil, name, pf.Bool())) pf.SetBool(ac.DefaultBool(name, pf.Bool()))
case reflect.Struct: case reflect.Struct:
default: default:
// do nothing here // do nothing here
@ -433,105 +432,105 @@ func newAppConfig(appConfigProvider, appConfigPath string) (*beegoAppConfig, err
return &beegoAppConfig{innerConfig: ac}, nil return &beegoAppConfig{innerConfig: ac}, nil
} }
func (b *beegoAppConfig) Set(ctx context2.Context, key, val string) error { func (b *beegoAppConfig) Set(key, val string) error {
if err := b.innerConfig.Set(nil, BConfig.RunMode+"::"+key, val); err != nil { if err := b.innerConfig.Set(BConfig.RunMode+"::"+key, val); err != nil {
return b.innerConfig.Set(nil, key, val) return b.innerConfig.Set(key, val)
} }
return nil return nil
} }
func (b *beegoAppConfig) String(ctx context2.Context, key string) (string, error) { func (b *beegoAppConfig) String(key string) (string, error) {
if v, err := b.innerConfig.String(nil, BConfig.RunMode+"::"+key); v != "" && err == nil { if v, err := b.innerConfig.String(BConfig.RunMode + "::" + key); v != "" && err == nil {
return v, nil return v, nil
} }
return b.innerConfig.String(nil, key) return b.innerConfig.String(key)
} }
func (b *beegoAppConfig) Strings(ctx context2.Context, key string) ([]string, error) { func (b *beegoAppConfig) Strings(key string) ([]string, error) {
if v, err := b.innerConfig.Strings(nil, BConfig.RunMode+"::"+key); len(v) > 0 && err == nil { if v, err := b.innerConfig.Strings(BConfig.RunMode + "::" + key); len(v) > 0 && err == nil {
return v, nil return v, nil
} }
return b.innerConfig.Strings(nil, key) return b.innerConfig.Strings(key)
} }
func (b *beegoAppConfig) Int(ctx context2.Context, key string) (int, error) { func (b *beegoAppConfig) Int(key string) (int, error) {
if v, err := b.innerConfig.Int(nil, BConfig.RunMode+"::"+key); err == nil { if v, err := b.innerConfig.Int(BConfig.RunMode + "::" + key); err == nil {
return v, nil return v, nil
} }
return b.innerConfig.Int(nil, key) return b.innerConfig.Int(key)
} }
func (b *beegoAppConfig) Int64(ctx context2.Context, key string) (int64, error) { func (b *beegoAppConfig) Int64(key string) (int64, error) {
if v, err := b.innerConfig.Int64(nil, BConfig.RunMode+"::"+key); err == nil { if v, err := b.innerConfig.Int64(BConfig.RunMode + "::" + key); err == nil {
return v, nil return v, nil
} }
return b.innerConfig.Int64(nil, key) return b.innerConfig.Int64(key)
} }
func (b *beegoAppConfig) Bool(ctx context2.Context, key string) (bool, error) { func (b *beegoAppConfig) Bool(key string) (bool, error) {
if v, err := b.innerConfig.Bool(nil, BConfig.RunMode+"::"+key); err == nil { if v, err := b.innerConfig.Bool(BConfig.RunMode + "::" + key); err == nil {
return v, nil return v, nil
} }
return b.innerConfig.Bool(nil, key) return b.innerConfig.Bool(key)
} }
func (b *beegoAppConfig) Float(ctx context2.Context, key string) (float64, error) { func (b *beegoAppConfig) Float(key string) (float64, error) {
if v, err := b.innerConfig.Float(nil, BConfig.RunMode+"::"+key); err == nil { if v, err := b.innerConfig.Float(BConfig.RunMode + "::" + key); err == nil {
return v, nil return v, nil
} }
return b.innerConfig.Float(nil, key) return b.innerConfig.Float(key)
} }
func (b *beegoAppConfig) DefaultString(ctx context2.Context, key string, defaultVal string) string { func (b *beegoAppConfig) DefaultString(key string, defaultVal string) string {
if v, err := b.String(nil, key); v != "" && err == nil { if v, err := b.String(key); v != "" && err == nil {
return v return v
} }
return defaultVal return defaultVal
} }
func (b *beegoAppConfig) DefaultStrings(ctx context2.Context, key string, defaultVal []string) []string { func (b *beegoAppConfig) DefaultStrings(key string, defaultVal []string) []string {
if v, err := b.Strings(ctx, key); len(v) != 0 && err == nil { if v, err := b.Strings(key); len(v) != 0 && err == nil {
return v return v
} }
return defaultVal return defaultVal
} }
func (b *beegoAppConfig) DefaultInt(ctx context2.Context, key string, defaultVal int) int { func (b *beegoAppConfig) DefaultInt(key string, defaultVal int) int {
if v, err := b.Int(ctx, key); err == nil { if v, err := b.Int(key); err == nil {
return v return v
} }
return defaultVal return defaultVal
} }
func (b *beegoAppConfig) DefaultInt64(ctx context2.Context, key string, defaultVal int64) int64 { func (b *beegoAppConfig) DefaultInt64(key string, defaultVal int64) int64 {
if v, err := b.Int64(ctx, key); err == nil { if v, err := b.Int64(key); err == nil {
return v return v
} }
return defaultVal return defaultVal
} }
func (b *beegoAppConfig) DefaultBool(ctx context2.Context, key string, defaultVal bool) bool { func (b *beegoAppConfig) DefaultBool(key string, defaultVal bool) bool {
if v, err := b.Bool(ctx, key); err == nil { if v, err := b.Bool(key); err == nil {
return v return v
} }
return defaultVal return defaultVal
} }
func (b *beegoAppConfig) DefaultFloat(ctx context2.Context, key string, defaultVal float64) float64 { func (b *beegoAppConfig) DefaultFloat(key string, defaultVal float64) float64 {
if v, err := b.Float(ctx, key); err == nil { if v, err := b.Float(key); err == nil {
return v return v
} }
return defaultVal return defaultVal
} }
func (b *beegoAppConfig) DIY(ctx context2.Context, key string) (interface{}, error) { func (b *beegoAppConfig) DIY(key string) (interface{}, error) {
return b.innerConfig.DIY(nil, key) return b.innerConfig.DIY(key)
} }
func (b *beegoAppConfig) GetSection(ctx context2.Context, section string) (map[string]string, error) { func (b *beegoAppConfig) GetSection(section string) (map[string]string, error) {
return b.innerConfig.GetSection(nil, section) return b.innerConfig.GetSection(section)
} }
func (b *beegoAppConfig) SaveConfigFile(ctx context2.Context, filename string) error { func (b *beegoAppConfig) SaveConfigFile(filename string) error {
return b.innerConfig.SaveConfigFile(nil, filename) return b.innerConfig.SaveConfigFile(filename)
} }

View File

@ -111,12 +111,12 @@ func TestAssignConfig_02(t *testing.T) {
func TestAssignConfig_03(t *testing.T) { func TestAssignConfig_03(t *testing.T) {
jcf := &beeJson.JSONConfig{} jcf := &beeJson.JSONConfig{}
ac, _ := jcf.ParseData([]byte(`{"AppName":"beego"}`)) ac, _ := jcf.ParseData([]byte(`{"AppName":"beego"}`))
ac.Set(nil, "AppName", "test_app") ac.Set("AppName", "test_app")
ac.Set(nil, "RunMode", "online") ac.Set("RunMode", "online")
ac.Set(nil, "StaticDir", "download:down download2:down2") ac.Set("StaticDir", "download:down download2:down2")
ac.Set(nil, "StaticExtensionsToGzip", ".css,.js,.html,.jpg,.png") ac.Set("StaticExtensionsToGzip", ".css,.js,.html,.jpg,.png")
ac.Set(nil, "StaticCacheFileSize", "87456") ac.Set("StaticCacheFileSize", "87456")
ac.Set(nil, "StaticCacheFileNum", "1254") ac.Set("StaticCacheFileNum", "1254")
assignConfig(ac) assignConfig(ac)
t.Logf("%#v", BConfig) t.Logf("%#v", BConfig)

View File

@ -1,7 +1,6 @@
package web package web
import ( import (
context2 "context"
"encoding/json" "encoding/json"
"mime" "mime"
"net/http" "net/http"
@ -48,7 +47,7 @@ func registerDefaultErrorHandler() error {
func registerSession() error { func registerSession() error {
if BConfig.WebConfig.Session.SessionOn { if BConfig.WebConfig.Session.SessionOn {
var err error var err error
sessionConfig, err := AppConfig.String(nil, "sessionConfig") sessionConfig, err := AppConfig.String("sessionConfig")
conf := new(session.ManagerConfig) conf := new(session.ManagerConfig)
if sessionConfig == "" || err != nil { if sessionConfig == "" || err != nil {
conf.CookieName = BConfig.WebConfig.Session.SessionName conf.CookieName = BConfig.WebConfig.Session.SessionName
@ -89,9 +88,9 @@ func registerTemplate() error {
func registerGzip() error { func registerGzip() error {
if BConfig.EnableGzip { if BConfig.EnableGzip {
context.InitGzip( context.InitGzip(
AppConfig.DefaultInt(context2.Background(), "gzipMinLength", -1), AppConfig.DefaultInt("gzipMinLength", -1),
AppConfig.DefaultInt(context2.Background(), "gzipCompressLevel", -1), AppConfig.DefaultInt("gzipCompressLevel", -1),
AppConfig.DefaultStrings(context2.Background(), "includedMethods", []string{"GET"}), AppConfig.DefaultStrings("includedMethods", []string{"GET"}),
) )
} }
return nil return nil

View File

@ -15,7 +15,6 @@
package web package web
import ( import (
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@ -517,7 +516,7 @@ func genRouterCode(pkgRealpath string) {
} }
defer f.Close() defer f.Close()
routersDir := AppConfig.DefaultString(context.Background(), "routersdir", "routers") routersDir := AppConfig.DefaultString("routersdir", "routers")
content := strings.Replace(globalRouterTemplate, "{{.globalinfo}}", globalinfo, -1) content := strings.Replace(globalRouterTemplate, "{{.globalinfo}}", globalinfo, -1)
content = strings.Replace(content, "{{.routersDir}}", routersDir, -1) content = strings.Replace(content, "{{.routersDir}}", routersDir, -1)
content = strings.Replace(content, "{{.globalimport}}", globalimport, -1) content = strings.Replace(content, "{{.globalimport}}", globalimport, -1)
@ -586,7 +585,7 @@ func getpathTime(pkgRealpath string) (lastupdate int64, err error) {
func getRouterDir(pkgRealpath string) string { func getRouterDir(pkgRealpath string) string {
dir := filepath.Dir(pkgRealpath) dir := filepath.Dir(pkgRealpath)
for { for {
routersDir := AppConfig.DefaultString(context.Background(), "routersdir", "routers") routersDir := AppConfig.DefaultString("routersdir", "routers")
d := filepath.Join(dir, routersDir) d := filepath.Join(dir, routersDir)
if utils.FileExists(d) { if utils.FileExists(d) {
return d return d

View File

@ -15,7 +15,6 @@
package web package web
import ( import (
"context"
"errors" "errors"
"fmt" "fmt"
"html" "html"
@ -161,17 +160,17 @@ func NotNil(a interface{}) (isNil bool) {
func GetConfig(returnType, key string, defaultVal interface{}) (value interface{}, err error) { func GetConfig(returnType, key string, defaultVal interface{}) (value interface{}, err error) {
switch returnType { switch returnType {
case "String": case "String":
value, err = AppConfig.String(context.Background(), key) value, err = AppConfig.String(key)
case "Bool": case "Bool":
value, err = AppConfig.Bool(context.Background(), key) value, err = AppConfig.Bool(key)
case "Int": case "Int":
value, err = AppConfig.Int(context.Background(), key) value, err = AppConfig.Int(key)
case "Int64": case "Int64":
value, err = AppConfig.Int64(context.Background(), key) value, err = AppConfig.Int64(key)
case "Float": case "Float":
value, err = AppConfig.Float(context.Background(), key) value, err = AppConfig.Float(key)
case "DIY": case "DIY":
value, err = AppConfig.DIY(context.Background(), key) value, err = AppConfig.DIY(key)
default: default:
err = errors.New("config keys must be of type String, Bool, Int, Int64, Float, or DIY") err = errors.New("config keys must be of type String, Bool, Int, Int64, Float, or DIY")
} }