github.com/wangyougui/gf/v2@v2.6.5/frame/gins/gins_view.go (about)

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