| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- package configure
-
- import (
- "time"
-
- "git.x2erp.com/qdy/go-base/config"
- )
-
- // AuthType 认证类型
- type AuthType string
-
- const (
- // AuthTypeBasic Basic认证
- AuthTypeBasic AuthType = "basic"
- // AuthTypeToken Token认证
- AuthTypeToken AuthType = "token"
- )
-
- // ClientConfig 客户端配置
- type ClientConfig struct {
- // BaseURL 配置中心基础URL
- BaseURL string `json:"baseURL" yaml:"baseURL"`
-
- // AuthType 认证类型
- AuthType AuthType `json:"authType" yaml:"authType"`
-
- // Basic认证配置
- Username string `json:"username,omitempty" yaml:"username,omitempty"`
- Password string `json:"password,omitempty" yaml:"password,omitempty"`
-
- // Token认证配置
- Token string `json:"token,omitempty" yaml:"token,omitempty"`
-
- // HTTP配置
- HTTPTimeout time.Duration `json:"httpTimeout,omitempty" yaml:"httpTimeout,omitempty"`
- Insecure bool `json:"insecure,omitempty" yaml:"insecure,omitempty"`
- }
-
- // DefaultConfig 返回默认配置
- // 从全局配置中获取ConfigureConfig的URL和认证凭证
- func DefaultConfig() ClientConfig {
- cfg := config.GetConfigureConfig()
- clientCfg := ClientConfig{
- BaseURL: cfg.Url,
- HTTPTimeout: 30 * time.Second,
- Insecure: false,
- }
-
- // 优先使用Token认证,其次使用Basic认证
- if cfg.Token != "" {
- clientCfg.AuthType = AuthTypeToken
- clientCfg.Token = cfg.Token
- } else if cfg.Username != "" && cfg.Password != "" {
- clientCfg.AuthType = AuthTypeBasic
- clientCfg.Username = cfg.Username
- clientCfg.Password = cfg.Password
- } else {
- // 默认使用Token,但Token为空(向后兼容,可能使用默认token)
- clientCfg.AuthType = AuthTypeToken
- clientCfg.Token = cfg.Token // 可能为空,由Validate检查
- }
-
- return clientCfg
- }
-
- // Validate 验证配置
- func (c *ClientConfig) Validate() error {
- if c.BaseURL == "" {
- return ErrConfigInvalidURL
- }
-
- // 如果AuthType未指定,根据提供的凭证推断
- if c.AuthType == "" {
- if c.Token != "" {
- c.AuthType = AuthTypeToken
- } else if c.Username != "" && c.Password != "" {
- c.AuthType = AuthTypeBasic
- } else {
- return ErrConfigInvalidAuth
- }
- }
-
- // 验证指定AuthType的凭证
- switch c.AuthType {
- case AuthTypeBasic:
- if c.Username == "" || c.Password == "" {
- return ErrConfigInvalidAuth
- }
- case AuthTypeToken:
- if c.Token == "" {
- return ErrConfigInvalidAuth
- }
- default:
- return ErrConfigInvalidAuthType
- }
-
- return nil
- }
|