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" // AuthTypeNone 无认证(用于公开接口) AuthTypeNone AuthType = "none" ) // 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 { // 无认证(用于公开接口) clientCfg.AuthType = AuthTypeNone } 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 { c.AuthType = AuthTypeNone // 无认证 } } // 验证指定AuthType的凭证 switch c.AuthType { case AuthTypeBasic: if c.Username == "" || c.Password == "" { return ErrConfigInvalidAuth } case AuthTypeToken: if c.Token == "" { return ErrConfigInvalidAuth } case AuthTypeNone: // 无认证,无需验证凭证 default: return ErrConfigInvalidAuthType } return nil }