github.com/qiniu/go-sdk/v7@v7.27.0/internal/configfile/config_file.go (about) 1 package configfile 2 3 import ( 4 "errors" 5 "path/filepath" 6 "strings" 7 "sync" 8 9 "github.com/BurntSushi/toml" 10 "github.com/qiniu/go-sdk/v7/internal/env" 11 ) 12 13 type profileConfig struct { 14 AccessKey string `toml:"access_key"` 15 SecretKey string `toml:"secret_key"` 16 BucketURL interface{} `toml:"bucket_url"` 17 DisableSecureProtocol bool `toml:"disable_secure_protocol"` 18 } 19 20 var ( 21 profileConfigs map[string]*profileConfig 22 profileConfigsError error 23 profileConfigsOnce sync.Once 24 ErrInvalidBucketUrl = errors.New("invalid bucket url") 25 ) 26 27 func CredentialsFromConfigFile() (string, string, error) { 28 profile, err := getProfile() 29 if err != nil || profile == nil { 30 return "", "", err 31 } else if profile.AccessKey == "" || profile.SecretKey == "" { 32 return "", "", nil 33 } 34 return profile.AccessKey, profile.SecretKey, nil 35 } 36 37 func BucketURLsFromConfigFile() ([]string, error) { 38 profile, err := getProfile() 39 if err != nil || profile == nil { 40 return nil, err 41 } else if profile.BucketURL == "" { 42 return nil, nil 43 } 44 switch u := profile.BucketURL.(type) { 45 case string: 46 return strings.Split(u, ","), nil 47 case []interface{}: 48 var bucketUrls []string 49 for _, v := range u { 50 if s, ok := v.(string); ok { 51 bucketUrls = append(bucketUrls, s) 52 } else { 53 return nil, ErrInvalidBucketUrl 54 } 55 } 56 return bucketUrls, nil 57 } 58 return nil, ErrInvalidBucketUrl 59 } 60 61 func DisableSecureProtocolFromConfigFile() (bool, error) { 62 profile, err := getProfile() 63 if err != nil || profile == nil { 64 return false, err 65 } 66 return profile.DisableSecureProtocol, nil 67 } 68 69 func getProfile() (*profileConfig, error) { 70 if err := load(); err != nil { 71 return nil, err 72 } 73 profileName := env.ProfileFromEnvironment() 74 if profileName == "" { 75 profileName = "default" 76 } 77 profile, ok := profileConfigs[profileName] 78 if !ok || profile == nil { 79 return nil, nil 80 } 81 return profile, nil 82 } 83 84 func load() error { 85 profileConfigsOnce.Do(func() { 86 profileConfigsError = _load() 87 }) 88 return profileConfigsError 89 } 90 91 func _load() error { 92 configFilePath := env.ConfigFileFromEnvironment() 93 if configFilePath == "" { 94 configFilePath = getDefaultConfigFilePath() 95 } 96 _, err := toml.DecodeFile(configFilePath, &profileConfigs) 97 return err 98 } 99 100 func getDefaultConfigFilePath() string { 101 homeDir, err := userHomeDir() 102 if err != nil { 103 homeDir = "" 104 } 105 return filepath.Join(homeDir, ".qiniu", "config.toml") 106 }