github.com/weaveworks/common@v0.0.0-20230728070032-dd9e68f319d5/aws/config.go (about) 1 package aws 2 3 import ( 4 "fmt" 5 "net" 6 "net/http" 7 "net/url" 8 "os" 9 "strings" 10 "time" 11 12 "github.com/aws/aws-sdk-go/aws" 13 "github.com/aws/aws-sdk-go/aws/credentials" 14 ) 15 16 // ConfigFromURL returns AWS config from given URL. It expects escaped 17 // AWS Access key ID & Secret Access Key to be encoded in the URL. It 18 // also expects region specified as a host (letting AWS generate full 19 // endpoint) or fully valid endpoint with dummy region assumed (e.g 20 // for URLs to emulated services). 21 func ConfigFromURL(awsURL *url.URL) (*aws.Config, error) { 22 config := aws.NewConfig(). 23 // Use a custom http.Client with the golang defaults but also specifying 24 // MaxIdleConnsPerHost because of a bug in golang https://github.com/golang/go/issues/13801 25 // where MaxIdleConnsPerHost does not work as expected. 26 WithHTTPClient(&http.Client{ 27 Transport: &http.Transport{ 28 Proxy: http.ProxyFromEnvironment, 29 DialContext: (&net.Dialer{ 30 Timeout: 30 * time.Second, 31 KeepAlive: 30 * time.Second, 32 DualStack: true, 33 }).DialContext, 34 MaxIdleConns: 100, 35 IdleConnTimeout: 90 * time.Second, 36 MaxIdleConnsPerHost: 100, 37 TLSHandshakeTimeout: 3 * time.Second, 38 ExpectContinueTimeout: 1 * time.Second, 39 }, 40 }) 41 42 if awsURL.User != nil { 43 username := awsURL.User.Username() 44 password, _ := awsURL.User.Password() 45 46 // We request at least the username or password being set to enable the static credentials. 47 if username != "" || password != "" { 48 config = config.WithCredentials(credentials.NewStaticCredentials(username, password, "")) 49 } 50 } 51 52 if strings.Contains(awsURL.Host, ".") { 53 region := os.Getenv("AWS_REGION") 54 if region == "" { 55 region = "dummy" 56 } 57 if awsURL.Scheme == "https" { 58 return config.WithEndpoint(fmt.Sprintf("https://%s", awsURL.Host)).WithRegion(region), nil 59 } 60 return config.WithEndpoint(fmt.Sprintf("http://%s", awsURL.Host)).WithRegion(region), nil 61 } 62 63 // Let AWS generate default endpoint based on region passed as a host in URL. 64 return config.WithRegion(awsURL.Host), nil 65 }