No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

config.go 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package configure
  2. import (
  3. "time"
  4. "git.x2erp.com/qdy/go-base/config"
  5. )
  6. // AuthType 认证类型
  7. type AuthType string
  8. const (
  9. // AuthTypeBasic Basic认证
  10. AuthTypeBasic AuthType = "basic"
  11. // AuthTypeToken Token认证
  12. AuthTypeToken AuthType = "token"
  13. )
  14. // ClientConfig 客户端配置
  15. type ClientConfig struct {
  16. // BaseURL 配置中心基础URL
  17. BaseURL string `json:"baseURL" yaml:"baseURL"`
  18. // AuthType 认证类型
  19. AuthType AuthType `json:"authType" yaml:"authType"`
  20. // Basic认证配置
  21. Username string `json:"username,omitempty" yaml:"username,omitempty"`
  22. Password string `json:"password,omitempty" yaml:"password,omitempty"`
  23. // Token认证配置
  24. Token string `json:"token,omitempty" yaml:"token,omitempty"`
  25. // HTTP配置
  26. HTTPTimeout time.Duration `json:"httpTimeout,omitempty" yaml:"httpTimeout,omitempty"`
  27. Insecure bool `json:"insecure,omitempty" yaml:"insecure,omitempty"`
  28. }
  29. // DefaultConfig 返回默认配置
  30. // 从全局配置中获取ConfigureConfig的URL和认证凭证
  31. func DefaultConfig() ClientConfig {
  32. cfg := config.GetConfigureConfig()
  33. clientCfg := ClientConfig{
  34. BaseURL: cfg.Url,
  35. HTTPTimeout: 30 * time.Second,
  36. Insecure: false,
  37. }
  38. // 优先使用Token认证,其次使用Basic认证
  39. if cfg.Token != "" {
  40. clientCfg.AuthType = AuthTypeToken
  41. clientCfg.Token = cfg.Token
  42. } else if cfg.Username != "" && cfg.Password != "" {
  43. clientCfg.AuthType = AuthTypeBasic
  44. clientCfg.Username = cfg.Username
  45. clientCfg.Password = cfg.Password
  46. } else {
  47. // 默认使用Token,但Token为空(向后兼容,可能使用默认token)
  48. clientCfg.AuthType = AuthTypeToken
  49. clientCfg.Token = cfg.Token // 可能为空,由Validate检查
  50. }
  51. return clientCfg
  52. }
  53. // Validate 验证配置
  54. func (c *ClientConfig) Validate() error {
  55. if c.BaseURL == "" {
  56. return ErrConfigInvalidURL
  57. }
  58. // 如果AuthType未指定,根据提供的凭证推断
  59. if c.AuthType == "" {
  60. if c.Token != "" {
  61. c.AuthType = AuthTypeToken
  62. } else if c.Username != "" && c.Password != "" {
  63. c.AuthType = AuthTypeBasic
  64. } else {
  65. return ErrConfigInvalidAuth
  66. }
  67. }
  68. // 验证指定AuthType的凭证
  69. switch c.AuthType {
  70. case AuthTypeBasic:
  71. if c.Username == "" || c.Password == "" {
  72. return ErrConfigInvalidAuth
  73. }
  74. case AuthTypeToken:
  75. if c.Token == "" {
  76. return ErrConfigInvalidAuth
  77. }
  78. default:
  79. return ErrConfigInvalidAuthType
  80. }
  81. return nil
  82. }