gins_view.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gins
  7. import (
  8. "context"
  9. "fmt"
  10. "github.com/gogf/gf/v2/internal/consts"
  11. "github.com/gogf/gf/v2/internal/intlog"
  12. "github.com/gogf/gf/v2/os/gview"
  13. "github.com/gogf/gf/v2/util/gutil"
  14. )
  15. const (
  16. frameCoreComponentNameViewer = "gf.core.component.viewer"
  17. )
  18. // View returns an instance of View with default settings.
  19. // The parameter `name` is the name for the instance.
  20. // Note that it panics if any error occurs duration instance creating.
  21. func View(name ...string) *gview.View {
  22. instanceName := gview.DefaultName
  23. if len(name) > 0 && name[0] != "" {
  24. instanceName = name[0]
  25. }
  26. instanceKey := fmt.Sprintf("%s.%s", frameCoreComponentNameViewer, instanceName)
  27. return localInstances.GetOrSetFuncLock(instanceKey, func() interface{} {
  28. return getViewInstance(instanceName)
  29. }).(*gview.View)
  30. }
  31. func getViewInstance(name ...string) *gview.View {
  32. var (
  33. err error
  34. ctx = context.Background()
  35. instanceName = gview.DefaultName
  36. )
  37. if len(name) > 0 && name[0] != "" {
  38. instanceName = name[0]
  39. }
  40. view := gview.Instance(instanceName)
  41. if Config().Available(ctx) {
  42. var (
  43. configMap map[string]interface{}
  44. configNodeName = consts.ConfigNodeNameViewer
  45. )
  46. if configMap, err = Config().Data(ctx); err != nil {
  47. intlog.Errorf(ctx, `retrieve config data map failed: %+v`, err)
  48. }
  49. if len(configMap) > 0 {
  50. if v, _ := gutil.MapPossibleItemByKey(configMap, consts.ConfigNodeNameViewer); v != "" {
  51. configNodeName = v
  52. }
  53. }
  54. configMap = Config().MustGet(ctx, fmt.Sprintf(`%s.%s`, configNodeName, instanceName)).Map()
  55. if len(configMap) == 0 {
  56. configMap = Config().MustGet(ctx, configNodeName).Map()
  57. }
  58. if len(configMap) > 0 {
  59. if err = view.SetConfigWithMap(configMap); err != nil {
  60. panic(err)
  61. }
  62. }
  63. }
  64. return view
  65. }