1
0
mirror of https://github.com/gogf/gf.git synced 2025-04-05 11:18:50 +08:00

improve configuration read from package frame/gins

This commit is contained in:
John Guo 2022-02-14 11:46:20 +08:00
parent a887cedb99
commit 1f9d86f015
7 changed files with 128 additions and 128 deletions

View File

@ -13,25 +13,19 @@
// Redis Chinese Documentation: http://redisdoc.com/
package gredis
import (
"github.com/gogf/gf/v2/errors/gcode"
"github.com/gogf/gf/v2/errors/gerror"
)
// New creates and returns a redis client.
// It creates a default redis adapter of go-redis.
func New(config ...*Config) (*Redis, error) {
if len(config) > 0 {
if len(config) > 0 && config[0] != nil {
// Redis client with go redis implements adapter from given configuration.
return &Redis{adapter: NewAdapterGoRedis(config[0])}, nil
}
configFromGlobal, ok := GetConfig()
if !ok {
return nil, gerror.NewCode(
gcode.CodeMissingConfiguration,
`configuration not found for creating Redis client`,
)
// Redis client with go redis implements adapter from package configuration.
if configFromGlobal, ok := GetConfig(); ok {
return &Redis{adapter: NewAdapterGoRedis(configFromGlobal)}, nil
}
return &Redis{adapter: NewAdapterGoRedis(configFromGlobal)}, nil
// Redis client with empty adapter.
return &Redis{}, nil
}
// NewWithAdapter creates and returns a redis client with given adapter.

View File

@ -180,19 +180,18 @@ func parseDBConfigNode(value interface{}) *gdb.ConfigNode {
if !ok {
return nil
}
node := &gdb.ConfigNode{}
err := gconv.Struct(nodeMap, node)
var (
node = &gdb.ConfigNode{}
err = gconv.Struct(nodeMap, node)
)
if err != nil {
panic(err)
}
// Be compatible with old version.
if _, v := gutil.MapPossibleItemByKey(nodeMap, "LinkInfo"); v != nil {
node.Link = gconv.String(v)
}
// Find possible `Link` configuration content.
if _, v := gutil.MapPossibleItemByKey(nodeMap, "Link"); v != nil {
node.Link = gconv.String(v)
}
// Parse link syntax.
// Parse `Link` configuration syntax.
if node.Link != "" && node.Type == "" {
match, _ := gregex.MatchString(`([a-z]+):(.+)`, node.Link)
if len(match) == 3 {

View File

@ -18,9 +18,7 @@ const (
// HttpClient returns an instance of http client with specified name.
func HttpClient(name ...interface{}) *gclient.Client {
var (
instanceKey = fmt.Sprintf("%s.%v", frameCoreComponentNameHttpClient, name)
)
var instanceKey = fmt.Sprintf("%s.%v", frameCoreComponentNameHttpClient, name)
return localInstances.GetOrSetFuncLock(instanceKey, func() interface{} {
return gclient.New()
}).(*gclient.Client)

View File

@ -11,7 +11,7 @@ import (
"fmt"
"github.com/gogf/gf/v2/database/gredis"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/internal/intlog"
"github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/gutil"
)
@ -25,6 +25,7 @@ const (
// Note that it panics if any error occurs duration instance creating.
func Redis(name ...string) *gredis.Redis {
var (
err error
ctx = context.Background()
group = gredis.DefaultGroupName
)
@ -37,35 +38,32 @@ func Redis(name ...string) *gredis.Redis {
if _, ok := gredis.GetConfig(group); ok {
return gredis.Instance(group)
}
// Or else, it parses the default configuration file and returns a new redis instance.
var (
configMap map[string]interface{}
)
if configData, err := Config().Data(ctx); err != nil {
panic(gerror.Wrap(err, `retrieving redis configuration failed`))
} else {
if _, v := gutil.MapPossibleItemByKey(configData, configNodeNameRedis); v != nil {
if Config().Available(ctx) {
var (
configMap map[string]interface{}
redisConfig *gredis.Config
redisClient *gredis.Redis
)
if configMap, err = Config().Data(ctx); err != nil {
intlog.Errorf(ctx, `retrieve config data map failed: %+v`, err)
}
if _, v := gutil.MapPossibleItemByKey(configMap, configNodeNameRedis); v != nil {
configMap = gconv.Map(v)
}
}
if len(configMap) > 0 {
if v, ok := configMap[group]; ok {
redisConfig, err := gredis.ConfigFromMap(gconv.Map(v))
if err != nil {
panic(err)
if len(configMap) > 0 {
if v, ok := configMap[group]; ok {
if redisConfig, err = gredis.ConfigFromMap(gconv.Map(v)); err != nil {
panic(err)
}
}
redisClient, err := gredis.New(redisConfig)
if err != nil {
panic(err)
}
return redisClient
intlog.Printf(ctx, `missing configuration for redis group "%s"`, group)
} else {
panic(fmt.Sprintf(`missing configuration for redis group "%s"`, group))
intlog.Printf(ctx, `missing configuration for redis: "redis" node not found`)
}
} else {
panic(`missing configuration for redis: "redis" node not found`)
if redisClient, err = gredis.New(redisConfig); err != nil {
panic(err)
}
return redisClient
}
return nil
})

View File

@ -17,15 +17,16 @@ import (
)
const (
frameCoreComponentNameServer = "gf.core.component.server"
configNodeNameServer = "server"
configNodeNameServerSecondary = "httpserver"
frameCoreComponentNameServer = "gf.core.component.server" // Prefix for HTTP server instance.
configNodeNameServer = "server" // General version configuration item name.
configNodeNameServerSecondary = "httpserver" // New version configuration item name support from v2.
)
// Server returns an instance of http server with specified name.
// Note that it panics if any error occurs duration instance creating.
func Server(name ...interface{}) *ghttp.Server {
var (
err error
ctx = context.Background()
instanceName = ghttp.DefaultServerName
instanceKey = fmt.Sprintf("%s.%v", frameCoreComponentNameServer, name)
@ -34,57 +35,67 @@ func Server(name ...interface{}) *ghttp.Server {
instanceName = gconv.String(name[0])
}
return localInstances.GetOrSetFuncLock(instanceKey, func() interface{} {
s := ghttp.GetServer(instanceName)
// It ignores returned error to avoid file no found error while it's not necessary.
var (
serverConfigMap map[string]interface{}
serverLoggerConfigMap map[string]interface{}
configNodeName string
)
if configData, _ := Config().Data(ctx); len(configData) > 0 {
if v, _ := gutil.MapPossibleItemByKey(configData, configNodeNameServer); v != "" {
configNodeName = v
server := ghttp.GetServer(instanceName)
if Config().Available(ctx) {
// Server initialization from configuration.
var (
configMap map[string]interface{}
serverConfigMap map[string]interface{}
serverLoggerConfigMap map[string]interface{}
configNodeName string
)
if configMap, err = Config().Data(ctx); err != nil {
intlog.Errorf(ctx, `retrieve config data map failed: %+v`, err)
}
if configNodeName == "" {
if v, _ := gutil.MapPossibleItemByKey(configData, configNodeNameServerSecondary); v != "" {
// Find possible server configuration item by possible names.
if len(configMap) > 0 {
if v, _ := gutil.MapPossibleItemByKey(configMap, configNodeNameServer); v != "" {
configNodeName = v
}
if configNodeName == "" {
if v, _ := gutil.MapPossibleItemByKey(configMap, configNodeNameServerSecondary); v != "" {
configNodeName = v
}
}
}
// Server configuration.
serverConfigMap = Config().MustGet(
ctx,
fmt.Sprintf(`%s.%s`, configNodeName, server.GetName()),
).Map()
if len(serverConfigMap) == 0 {
serverConfigMap = Config().MustGet(ctx, configNodeName).Map()
}
if len(serverConfigMap) > 0 {
if err = server.SetConfigWithMap(serverConfigMap); err != nil {
panic(err)
}
} else {
// The configuration is not necessary, so it just prints internal logs.
intlog.Printf(
ctx,
`missing configuration from configuration component for HTTP server "%s"`,
instanceName,
)
}
// Server logger configuration checks.
serverLoggerConfigMap = Config().MustGet(
ctx,
fmt.Sprintf(`%s.%s.%s`, configNodeName, server.GetName(), configNodeNameLogger),
).Map()
if len(serverLoggerConfigMap) > 0 {
if err = server.Logger().SetConfigWithMap(serverLoggerConfigMap); err != nil {
panic(err)
}
}
}
// Server configuration.
certainConfigNodeName := fmt.Sprintf(`%s.%s`, configNodeName, s.GetName())
if v, _ := Config().Get(ctx, certainConfigNodeName); !v.IsEmpty() {
serverConfigMap = v.Map()
}
if len(serverConfigMap) == 0 {
if v, _ := Config().Get(ctx, configNodeName); !v.IsEmpty() {
serverConfigMap = v.Map()
}
}
if len(serverConfigMap) > 0 {
if err := s.SetConfigWithMap(serverConfigMap); err != nil {
panic(err)
}
} else {
// The configuration is not necessary, so it just prints internal logs.
intlog.Printf(ctx, `missing configuration from configuration component for HTTP server "%s"`, instanceName)
}
if s.GetName() == "" || s.GetName() == ghttp.DefaultServerName {
s.SetName(instanceName)
}
// Server logger configuration checks.
serverLoggerNodeName := fmt.Sprintf(`%s.%s.%s`, configNodeName, s.GetName(), configNodeNameLogger)
if v, _ := Config().Get(ctx, serverLoggerNodeName); !v.IsEmpty() {
serverLoggerConfigMap = v.Map()
}
if len(serverLoggerConfigMap) > 0 {
if err := s.Logger().SetConfigWithMap(serverLoggerConfigMap); err != nil {
panic(err)
}
// The server name is necessary. It sets a default server name is it is not configured.
if server.GetName() == "" || server.GetName() == ghttp.DefaultServerName {
server.SetName(instanceName)
}
// As it might use template feature,
// it initializes the view instance as well.
_ = getViewInstance()
return s
return server
}).(*ghttp.Server)
}

View File

@ -10,6 +10,7 @@ import (
"context"
"fmt"
"github.com/gogf/gf/v2/internal/intlog"
"github.com/gogf/gf/v2/os/gview"
"github.com/gogf/gf/v2/util/gutil"
)
@ -35,6 +36,7 @@ func View(name ...string) *gview.View {
func getViewInstance(name ...string) *gview.View {
var (
err error
ctx = context.Background()
instanceName = gview.DefaultName
)
@ -42,27 +44,27 @@ func getViewInstance(name ...string) *gview.View {
instanceName = name[0]
}
view := gview.Instance(instanceName)
// To avoid file no found error while it's not necessary.
var (
configMap map[string]interface{}
configNodeName = configNodeNameViewer
)
if configData, _ := Config().Data(ctx); len(configData) > 0 {
if v, _ := gutil.MapPossibleItemByKey(configData, configNodeNameViewer); v != "" {
configNodeName = v
if Config().Available(ctx) {
var (
configMap map[string]interface{}
configNodeName = configNodeNameViewer
)
if configMap, err = Config().Data(ctx); err != nil {
intlog.Errorf(ctx, `retrieve config data map failed: %+v`, err)
}
}
if v, _ := Config().Get(ctx, fmt.Sprintf(`%s.%s`, configNodeName, instanceName)); !v.IsEmpty() {
configMap = v.Map()
}
if len(configMap) == 0 {
if v, _ := Config().Get(ctx, configNodeName); !v.IsEmpty() {
configMap = v.Map()
if len(configMap) > 0 {
if v, _ := gutil.MapPossibleItemByKey(configMap, configNodeNameViewer); v != "" {
configNodeName = v
}
}
}
if len(configMap) > 0 {
if err := view.SetConfigWithMap(configMap); err != nil {
panic(err)
configMap = Config().MustGet(ctx, fmt.Sprintf(`%s.%s`, configNodeName, instanceName)).Map()
if len(configMap) == 0 {
configMap = Config().MustGet(ctx, configNodeName).Map()
}
if len(configMap) > 0 {
if err = view.SetConfigWithMap(configMap); err != nil {
panic(err)
}
}
}
return view

View File

@ -253,28 +253,26 @@ func (c *AdapterFile) getJson(fileName ...string) (configJson *gjson.Json, err e
} else {
configJson, err = gjson.LoadContent(content, true)
}
if err == nil {
configJson.SetViolenceCheck(c.violenceCheck)
// Add monitor for this configuration file,
// any changes of this file will refresh its cache in Config object.
if filePath != "" && !gres.Contains(filePath) {
_, err = gfsnotify.Add(filePath, func(event *gfsnotify.Event) {
c.jsonMap.Remove(usedFileName)
})
if err != nil {
return nil
}
}
return configJson
}
if err != nil {
if filePath != "" {
err = gerror.Wrapf(err, `load config file "%s" failed`, filePath)
} else {
err = gerror.Wrap(err, `load configuration failed`)
}
return nil
}
return nil
configJson.SetViolenceCheck(c.violenceCheck)
// Add monitor for this configuration file,
// any changes of this file will refresh its cache in Config object.
if filePath != "" && !gres.Contains(filePath) {
_, err = gfsnotify.Add(filePath, func(event *gfsnotify.Event) {
c.jsonMap.Remove(usedFileName)
})
if err != nil {
return nil
}
}
return configJson
})
if result != nil {
return result.(*gjson.Json), err