gins_view.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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/instance"
  12. "github.com/gogf/gf/v2/internal/intlog"
  13. "github.com/gogf/gf/v2/os/gview"
  14. "github.com/gogf/gf/v2/util/gutil"
  15. )
  16. // View returns an instance of View with default settings.
  17. // The parameter `name` is the name for the instance.
  18. // Note that it panics if any error occurs duration instance creating.
  19. func View(name ...string) *gview.View {
  20. instanceName := gview.DefaultName
  21. if len(name) > 0 && name[0] != "" {
  22. instanceName = name[0]
  23. }
  24. instanceKey := fmt.Sprintf("%s.%s", frameCoreComponentNameViewer, instanceName)
  25. return instance.GetOrSetFuncLock(instanceKey, func() interface{} {
  26. return getViewInstance(instanceName)
  27. }).(*gview.View)
  28. }
  29. func getViewInstance(name ...string) *gview.View {
  30. var (
  31. err error
  32. ctx = context.Background()
  33. instanceName = gview.DefaultName
  34. )
  35. if len(name) > 0 && name[0] != "" {
  36. instanceName = name[0]
  37. }
  38. view := gview.Instance(instanceName)
  39. if Config().Available(ctx) {
  40. var (
  41. configMap map[string]interface{}
  42. configNodeName = consts.ConfigNodeNameViewer
  43. )
  44. if configMap, err = Config().Data(ctx); err != nil {
  45. intlog.Errorf(ctx, `retrieve config data map failed: %+v`, err)
  46. }
  47. if len(configMap) > 0 {
  48. if v, _ := gutil.MapPossibleItemByKey(configMap, consts.ConfigNodeNameViewer); v != "" {
  49. configNodeName = v
  50. }
  51. }
  52. configMap = Config().MustGet(ctx, fmt.Sprintf(`%s.%s`, configNodeName, instanceName)).Map()
  53. if len(configMap) == 0 {
  54. configMap = Config().MustGet(ctx, configNodeName).Map()
  55. }
  56. if len(configMap) > 0 {
  57. if err = view.SetConfigWithMap(configMap); err != nil {
  58. panic(err)
  59. }
  60. }
  61. }
  62. return view
  63. }