github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/router/config.go (about)

     1  package router
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/volts-dev/volts/config"
     7  	"github.com/volts-dev/volts/logger"
     8  	"github.com/volts-dev/volts/registry"
     9  	"github.com/volts-dev/volts/registry/cacher"
    10  )
    11  
    12  const (
    13  	MODULE_DIR   = "module" // # 模块文件夹名称
    14  	STATIC_DIR   = "static"
    15  	TEMPLATE_DIR = "template"
    16  )
    17  
    18  var (
    19  	ControllerMethodNameMapper = func(name string) string {
    20  		name = strings.ToLower(name)
    21  		// 为特殊控制器提供固定的接口命名 比如Model.Read被占用的情款下改用Model.Api_Read
    22  		name = strings.Replace(name, "api_", "", 1)
    23  		return name
    24  	}
    25  )
    26  
    27  type (
    28  	Option func(*Config)
    29  	Config struct {
    30  		config.Config  `field:"-"`
    31  		Name           string             `field:"-"` // config name/path in config file
    32  		PrefixName     string             `field:"-"` // config prefix name
    33  		Logger         logger.ILogger     `field:"-"` // 实例
    34  		Router         *TRouter           `field:"-"`
    35  		Registry       registry.IRegistry `field:"-"`
    36  		RegistryCacher cacher.ICacher     `field:"-"` // registry cache
    37  
    38  		// mapping to config file
    39  		RecoverHandler    func(IContext) `field:"-"`
    40  		Recover           bool           `field:"recover"`
    41  		RouterTreePrinter bool           `field:"router_tree_printer"`
    42  		RequestPrinter    bool           `field:"request_printer"`
    43  		StaticDir         []string       `field:"static_dir"` // the static dir allow to visit
    44  		StaticExt         []string       `field:"static_ext"` // the static file format allow to visit
    45  		UsePprof          bool
    46  		UploadBuf         int `field:"upload_buf"` // 上传文件大小MB
    47  	}
    48  
    49  	GroupOption func(*GroupConfig)
    50  	GroupConfig struct {
    51  		Name          string // 当前源代码文件夹名称
    52  		_PrefixPath   string
    53  		FilePath      string // 当前源代码文件夹路径
    54  		IsService     bool   // 是否在registry注册为独立的服务
    55  		PathPrefix    string
    56  		StaticHandler func(IContext) `field:"-"`
    57  	}
    58  )
    59  
    60  func newConfig(opts ...Option) *Config {
    61  	cfg := &Config{
    62  		Logger:         log,
    63  		Recover:        true,
    64  		RecoverHandler: recoverHandler,
    65  		UploadBuf:      25,
    66  	}
    67  	cfg.Init(opts...)
    68  	config.Register(cfg)
    69  
    70  	if cfg.Registry == nil {
    71  		cfg.Registry = registry.Default()
    72  		cfg.RegistryCacher = cacher.New(cfg.Registry, registry.WithConfigPrefixName(cfg.String()))
    73  	}
    74  
    75  	return cfg
    76  }
    77  
    78  func (self *Config) String() string {
    79  	if len(self.PrefixName) > 0 {
    80  		return strings.Join([]string{self.PrefixName, "router"}, ".")
    81  	}
    82  	return self.Name
    83  }
    84  
    85  func (self *Config) Init(opts ...Option) {
    86  	for _, opt := range opts {
    87  		if opt != nil {
    88  			opt(self)
    89  		}
    90  	}
    91  }
    92  
    93  func (self *Config) Load() error {
    94  	return self.LoadToModel(self)
    95  }
    96  
    97  func (self *Config) Save(immed ...bool) error {
    98  	return self.SaveFromModel(self, immed...)
    99  }
   100  
   101  func Debug() Option {
   102  	return func(cfg *Config) {
   103  		cfg.Debug = true
   104  	}
   105  }
   106  
   107  func Logger() logger.ILogger {
   108  	return log
   109  }
   110  
   111  func WithNameMapper(fn func(string) string) config.Option {
   112  	return func(cfg *config.Config) {
   113  		ControllerMethodNameMapper = fn
   114  	}
   115  }
   116  
   117  func WithPprof() Option {
   118  	return func(cfg *Config) {
   119  		cfg.Router.RegisterGroup(pprofGroup())
   120  	}
   121  }
   122  
   123  // Register the service with a TTL
   124  func WithRoutesTreePrinter() Option {
   125  	return func(cfg *Config) {
   126  		cfg.RouterTreePrinter = true
   127  		//cfg.SetValue("print_router_tree", true)
   128  	}
   129  }
   130  
   131  // Register the service with a TTL
   132  func WithRequestPrinter() Option {
   133  	return func(cfg *Config) {
   134  		cfg.RequestPrinter = true
   135  		//cfg.SetValue("print_request", true)
   136  	}
   137  }
   138  
   139  func WithRecover(on bool) Option {
   140  	return func(cfg *Config) {
   141  		cfg.Recover = on
   142  	}
   143  }
   144  
   145  func WithRecoverHandler(handler func(IContext)) Option {
   146  	return func(cfg *Config) {
   147  		cfg.RecoverHandler = handler
   148  	}
   149  }
   150  
   151  func WithRegistry(r registry.IRegistry) Option {
   152  	return func(cfg *Config) {
   153  		cfg.Registry = r
   154  		cfg.RegistryCacher = cacher.New(r)
   155  	}
   156  }
   157  
   158  func WithStaticHandler(handler func(IContext)) GroupOption {
   159  	return func(cfg *GroupConfig) {
   160  		cfg.StaticHandler = handler
   161  	}
   162  }
   163  
   164  func WithCurrentModulePath() GroupOption {
   165  	return func(cfg *GroupConfig) {
   166  		cfg.FilePath, cfg.Name = curFilePath(4)
   167  	}
   168  }
   169  
   170  func WithGroupName(name string) GroupOption {
   171  	return func(cfg *GroupConfig) {
   172  		cfg.Name = name
   173  	}
   174  }
   175  
   176  // TODO 更名
   177  // default url"/abc"
   178  // PrefixPath url "/PrefixPath/abc"
   179  func WithGroupPathPrefix(prefixPath string) GroupOption {
   180  	return func(cfg *GroupConfig) {
   181  		cfg.PathPrefix = prefixPath
   182  	}
   183  }
   184  
   185  // 独立出来注册为单一微服务在registry里
   186  func WithAloneService(asService bool, servicsName string, prefix ...string) GroupOption {
   187  	return func(cfg *GroupConfig) {
   188  		cfg.Name = servicsName
   189  		cfg.IsService = asService
   190  		if len(prefix) > 0 {
   191  			cfg.PathPrefix = prefix[0]
   192  		}
   193  	}
   194  }
   195  
   196  // 修改Config.json的路径
   197  func WithConfigPrefixName(prefixName string) Option {
   198  	return func(cfg *Config) {
   199  		cfg.Unregister(cfg)
   200  		cfg.PrefixName = prefixName
   201  		cfg.Register(cfg)
   202  	}
   203  }