Brak opisu
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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. // AuthTypeNone 无认证(用于公开接口)
  14. AuthTypeNone AuthType = "none"
  15. )
  16. // ClientConfig 客户端配置
  17. type ClientConfig struct {
  18. // BaseURL 配置中心基础URL
  19. BaseURL string `json:"baseURL" yaml:"baseURL"`
  20. // AuthType 认证类型
  21. AuthType AuthType `json:"authType" yaml:"authType"`
  22. // Basic认证配置
  23. Username string `json:"username,omitempty" yaml:"username,omitempty"`
  24. Password string `json:"password,omitempty" yaml:"password,omitempty"`
  25. // Token认证配置
  26. Token string `json:"token,omitempty" yaml:"token,omitempty"`
  27. // HTTP配置
  28. HTTPTimeout time.Duration `json:"httpTimeout,omitempty" yaml:"httpTimeout,omitempty"`
  29. Insecure bool `json:"insecure,omitempty" yaml:"insecure,omitempty"`
  30. }
  31. // DefaultConfig 返回默认配置
  32. // 从全局配置中获取ConfigureConfig的URL和认证凭证
  33. func DefaultConfig() ClientConfig {
  34. cfg := config.GetConfigureConfig()
  35. clientCfg := ClientConfig{
  36. BaseURL: cfg.Url,
  37. HTTPTimeout: 30 * time.Second,
  38. Insecure: false,
  39. }
  40. // 优先使用Token认证,其次使用Basic认证,都没有则无认证
  41. if cfg.Token != "" {
  42. clientCfg.AuthType = AuthTypeToken
  43. clientCfg.Token = cfg.Token
  44. } else if cfg.Username != "" && cfg.Password != "" {
  45. clientCfg.AuthType = AuthTypeBasic
  46. clientCfg.Username = cfg.Username
  47. clientCfg.Password = cfg.Password
  48. } else {
  49. // 无认证(用于公开接口)
  50. clientCfg.AuthType = AuthTypeNone
  51. }
  52. return clientCfg
  53. }
  54. // Validate 验证配置
  55. func (c *ClientConfig) Validate() error {
  56. if c.BaseURL == "" {
  57. return ErrConfigInvalidURL
  58. }
  59. // 如果AuthType未指定,根据提供的凭证推断
  60. if c.AuthType == "" {
  61. if c.Token != "" {
  62. c.AuthType = AuthTypeToken
  63. } else if c.Username != "" && c.Password != "" {
  64. c.AuthType = AuthTypeBasic
  65. } else {
  66. c.AuthType = AuthTypeNone // 无认证
  67. }
  68. }
  69. // 验证指定AuthType的凭证
  70. switch c.AuthType {
  71. case AuthTypeBasic:
  72. if c.Username == "" || c.Password == "" {
  73. return ErrConfigInvalidAuth
  74. }
  75. case AuthTypeToken:
  76. if c.Token == "" {
  77. return ErrConfigInvalidAuth
  78. }
  79. case AuthTypeNone:
  80. // 无认证,无需验证凭证
  81. default:
  82. return ErrConfigInvalidAuthType
  83. }
  84. return nil
  85. }